一、redux 创建一个Store
// src/store.js
import { createStore } from 'redux';
const initialState = { count: 0 };
const reducer = (state = initialState, action) => {
switch (action.type) {
case 'INCREMENT':
return { count: state.count + 1 };
case 'DECREMENT':
return { count: state.count - 1 };
default:
return state;
}
};
const store = createStore(reducer);
export default store;
我们创建一个根组件,并在其中使用Provider组件来传递Redux store。我们在根组件中渲染Counter组件,并将它包裹在Provider组件中。
// src/App.js
import React from 'react';
import { Provider } from 'react-redux';
import store from './store';
import Counter from './Counter';
const App = () => {
return (
<Provider store={store}>
<Counter />
</Provider>
);
};
export default App;
二、react-redux
react-redux是一个为React应用程序提供与Redux集成的库。它提供了一组React组件和钩子,可以帮助我们将Redux store中的状态映射到React组件的props中,并将Redux action映射到React组件的事件处理程序中。
react-redux库的主要组件和API包括:
- Provider组件:Provider组件是一个高阶组件,它将Redux store作为prop传递给整个应用程序。我们只需要在应用程序的根组件中使用Provider组件,并将Redux store作为prop传递给它即可。
- connect函数:connect函数是一个高阶函数,它接受两个参数:mapStateToProps和mapDispatchToProps。mapStateToProps函数将Redux store中的状态映射到React组件的props中,而mapDispatchToProps函数将Redux action映射到React组件的事件处理程序中。connect函数返回一个高阶组件,它将mapStateToProps和mapDispatchToProps返回的结果作为props传递给原始的React组件。
- useSelector钩子:useSelector钩子是一个React钩子,它允许我们从Redux store中选择特定的状态,并在组件中使用它们。useSelector钩子接受一个选择器函数作为参数,并返回选择器函数返回的结果。
- useDispatch钩子:useDispatch钩子是一个React钩子,它允许我们在组件中分发Redux action。useDispatch钩子返回一个分发函数,我们可以在组件中使用它来分发Redux action。
使用react-redux库可以大大简化我们在React应用程序中使用Redux的过程。它提供了一组强大的工具和API,使得我们可以轻松地将Redux集成到React应用程序中,并管理应用程序的状态。
三、完整的demo
创建一个React组件来显示计数器的值和两个按钮,一个用于增加计数器的值,另一个用于减少计数器的值。我们使用react-redux库的connect函数将Redux store中的状态映射到组件的props中,并将Redux action映射到组件的事件处理程序中。
// src/Counter.js
import React from 'react';
import { connect } from 'react-redux';
const Counter = ({ count, increment, decrement }) => {
return (
<div>
<h1>Count: {count}</h1>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
</div>
);
};
const mapStateToProps = (state) => {
return {
count: state.count,
};
};
const mapDispatchToProps = (dispatch) => {
return {
increment: () => dispatch({ type: 'INCREMENT' }),
decrement: () => dispatch({ type: 'DECREMENT' }),
};
};
export default connect(mapStateToProps, mapDispatchToProps)(Counter);
四、使用React Hooks实现上面的功能
创建一个React组件来显示计数器的值和两个按钮,一个用于增加计数器的值,另一个用于减少计数器的值。我们使用react-redux库的useSelector钩子将Redux store中的状态选择出来,并使用useDispatch钩子将Redux action分发到Redux store中。
// src/Counter.js
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
const Counter = () => {
const count = useSelector((state) => state.count);
const dispatch = useDispatch();
const handleIncrement = () => {
dispatch({ type: 'INCREMENT' });
};
const handleDecrement = () => {
dispatch({ type: 'DECREMENT' });
};
return (
<div>
<h1>Count: {count}</h1>
<button onClick={handleIncrement}>Increment</button>
<button onClick={handleDecrement}>Decrement</button>
</div>
);
};
export default Counter;