注:新版 redux 用法中 使用useSelector、useDispatch替代connect,这里只做老用法的记录使用。
Redux最新用法参考 个人React专栏react初级学习
React-Redux是一个用于将React应用程序连接到Redux状态管理器的库。以下是React-Redux的简单用法示例:
- 安装React-Redux库
npm install react-redux
- 创建Redux store
创建Redux store,这是存储应用程序状态的地方。可以使用Redux createStore函数创建store。
import { createStore } from 'redux';
const initialState = {
count: 0
};
const reducer = (state = initialState, action) => {
switch (action.type) {
case 'INCREMENT':
return {
...state,
count: state.count + 1
};
case 'DECREMENT':
return {
...state,
count: state.count - 1
};
default:
return state;
}
};
const store = createStore(reducer);
- 创建React组件
创建一个React组件,将组件中需要的store中的状态传递给组件的props。可以使用React Redux提供的connect函数将组件连接到Redux store并订阅state更改。
import React from 'react';
import { connect } from 'react-redux';
const Counter = ({ count, increment, decrement }) => (
<div>
<h1>Count: {count}</h1>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
</div>
);
const mapStateToProps = state => ({
count: state.count
});
const mapDispatchToProps = {
increment: () => ({ type: 'INCREMENT' }),
decrement: () => ({ type: 'DECREMENT' })
};
export default connect(
mapStateToProps,
mapDispatchToProps