- Redux Tutorial
- Redux - Home
- Redux - Overview
- Redux - Installation
- Redux - Core Concepts
- Redux - Data Flow
- Redux - Store
- Redux - Actions
- Redux - Pure Functions
- Redux - Reducers
- Redux - Middleware
- Redux - Devtools
- Redux - Testing
- Redux - Integrate React
- Redux - React Example
- Redux Useful Resources
- Redux - Quick Guide
- Redux - Useful Resources
- Redux - Discussion
Redux - React 示例
这是一个 React 和 Redux 应用程序的小例子。您还可以尝试开发小型应用程序。下面给出了增加或减少计数器的示例代码 -
这是根文件,负责创建 store 并渲染我们的 React 应用程序组件。
/src/index.js
import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import { createStore } from 'redux';
import reducer from '../src/reducer/index'
import App from '../src/App'
import './index.css';
const store = createStore(
reducer,
window.__REDUX_DEVTOOLS_EXTENSION__ &&
window.__REDUX_DEVTOOLS_EXTENSION__()
)
render(
<Provider store = {store}>
<App />
</Provider>, document.getElementById('root')
)
这是我们的 React 根组件。它负责将计数器容器组件渲染为子组件。
/src/app.js
import React, { Component } from 'react';
import './App.css';
import Counter from '../src/container/appContainer';
class App extends Component {
render() {
return (
<div className = "App">
<header className = "App-header">
<Counter/>
</header>
</div>
);
}
}
export default App;
以下是容器组件,负责向 React 组件提供 Redux 的状态 -
/container/counterContainer.js
import { connect } from 'react-redux'
import Counter from '../component/counter'
import { increment, decrement, reset } from '../actions';
const mapStateToProps = (state) => {
return {
counter: state
};
};
const mapDispatchToProps = (dispatch) => {
return {
increment: () => dispatch(increment()),
decrement: () => dispatch(decrement()),
reset: () => dispatch(reset())
};
};
export default connect(mapStateToProps, mapDispatchToProps)(Counter);
下面给出的是负责视图部分的反应组件 -
/component/counter.js
import React, { Component } from 'react';
class Counter extends Component {
render() {
const {counter,increment,decrement,reset} = this.props;
return (
<div className = "App">
<div>{counter}</div>
<div>
<button onClick = {increment}>INCREMENT BY 1</button>
</div>
<div>
<button onClick = {decrement}>DECREMENT BY 1</button>
</div>
<button onClick = {reset}>RESET</button>
</div>
);
}
}
export default Counter;
以下是负责创建动作的动作创建者 -
/actions/index.js
export function increment() {
return {
type: 'INCREMENT'
}
}
export function decrement() {
return {
type: 'DECREMENT'
}
}
export function reset() {
return { type: 'RESET' }
}
下面,我们展示了负责更新 Redux 中状态的 reducer 文件的代码行。
reducer/index.js
const reducer = (state = 0, action) => {
switch (action.type) {
case 'INCREMENT': return state + 1
case 'DECREMENT': return state - 1
case 'RESET' : return 0 default: return state
}
}
export default reducer;
最初,该应用程序如下所示 -
当我单击增量两次时,输出屏幕将如下所示 -
当我们递减一次时,它会显示以下屏幕 -
重置将使应用程序返回到初始状态,即计数器值 0。如下所示 -
让我们了解当第一个增量操作发生时 Redux 开发工具会发生什么 -
应用程序的状态将移动到仅调度增量操作并跳过其余操作的时间。
我们鼓励自己开发一个小型的 Todo App 作为作业,并更好地理解 Redux 工具。