1、最开始我们先运行安装
npm install react-redux redux
2、我们定义一个action类型和一个action creator:
// actions.js
export const INCREMENT = 'INCREMENT';
export function increment() {
return { type: INCREMENT };
}
3、我们创建一个reducer来处理这个action:
import { INCREMENT } from './actions';
const initialState = {
count: 0
};
function counter(state = initialState, action) {
switch (action.type) {
case INCREMENT:
return { ...state, count: state.count + 1 };
default:
return state;
}
}
export default counter;
4、我们创建一个store并将reducer传递给它:
// store.js
import { createStore } from 'redux';
import counter from './reducers';
const store = createStore(counter);
export default store;
5、我们在React组件中使用useSelector
和useDispatch
:
import { useSelector, useDispatch } from 'react-redux';
import { increment } from '../src/store/actions';
function App() {
const count = useSelector(state => state.count);
const dispatch = useDispatch();
return (
<div className="App">
<p>Count: {count}</p>
<button onClick={() => dispatch(increment())}>Increment</button>
</div>
);
}
export default App;
6、将Provider 引入到主应用中,别忘记将 store引入并且当做参数传入
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import { Provider } from 'react-redux';
import store from './store';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>
);