使用Redux的步骤如下:
- 安装Redux以及相关插件
你需要在你的项目中安装React和Redux。
npm install --save react redux react-redux
- 创建store
在Redux中,store是一个存储了应用程序状态的对象。创建store可以使用createStore()方法。在创建store时,你需要指定reducer。reducer是一个接受旧状态和action作为参数,并返回新状态的函数。
import { createStore } from 'redux';
import rootReducer from './reducers/index';
const store = createStore(rootReducer);
- 创建reducer
reducer是一个纯函数,它接受旧的state和action,并返回新的state。在Redux中,一般情况下,reducer应该是一个纯函数,仅仅基于旧的state和action计算新的state。
const initialState = {
counter: 0
};
function rootReducer(state = initialState, action) {
switch(action.type) {
case 'INCREMENT':
return {
...state,
counter: state.counter + 1
}
case 'DECREMENT':
return {
...state,
counter: state.counter - 1
}
default:
return state;
}
}
export default rootReducer;
- 触发action
在Redux中,更改状态应该始终通过派发一个action对象来实现。你可以使用dispatch方法来派发一个action。
store.dispatch({ type: 'INCREMENT' });
- 连接React组件
在React中,你需要将store中的状态传递给组件。为此,你可以使用connect()方法来连接组件。connect()方法使用两个函数:mapStateToProps和mapDispatchToProps来创建一个高阶组件。
import { connect } from 'react-redux';
const mapStateToProps = state => ({
counter: state.counter
});
const mapDispatchToProps = dispatch => ({
increment: () => dispatch({ type: 'INCREMENT' }),
decrement: () => dispatch({ type: 'DECREMENT' })
});
export default connect(mapStateToProps, mapDispatchToProps)(ComponentName);
以上就是使用Redux的基本步骤。你可以在你的项目中根据需要进行更改和修改。
如何异步
在Redux中,dispatch函数通常只接受一个对象类型的参数,这个参数就是action,用来描述某个事件发生了什么。但是,有时候我们需要在action中执行一些异步操作,例如从后端获取数据。这时候,我们可以使用redux-thunk这个中间件,使得dispatch函数可以接收一个函数类型的参数。
具体来说,redux-thunk中间件可以让dispatch函数接收到一个返回函数的action,这个返回函数通常会在异步操作后再次调用dispatch函数,以更新Redux store中的状态。下面是一个使用redux-thunk的例子:
const fetchUser = userId => dispatch => {
dispatch({ type: 'FETCH_USER_REQUEST' });
fetch(`/users/${userId}`)
.then(response => response.json())
.then(user => {
dispatch({ type: 'FETCH_USER_SUCCESS', payload: user });
})
.catch(error => {
dispatch({ type: 'FETCH_USER_FAILURE', payload: error });
});
};
// 使用fetchUser函数来获取用户信息
dispatch(fetchUser(123));
在上面的代码中,我们定义了一个fetchUser函数,它返回了一个函数,这个函数接收dispatch函数作为参数,并在内部进行异步操作,最终通过调用dispatch函数来更新Redux store中的状态。可以看到,使用redux-thunk可以让我们更方便地进行异步操作,使得dispatch函数更加灵活,可以接受不同类型的参数。