首先使用 redux 创建商店,然后安装 react-redux 库以使用 react 进行状态管理。按照下面的代码一步一步来。
步骤 - 1
// redux.js
import { createStore } from 'redux';
const store = createStore(rootReducer);
export default store;
步骤 - 2
// rootReducer.js
import { combineReducers } from 'redux';
import todosReducer from './todosReducer';
const rootReducer = combineReducers({
todos: todosReducer,
});
export default rootReducer;
步骤 - 3
// todosReducer.js
const initState = {
loading: false,
todos: [],
todo: null,
};
const todosReducer = (state = initState, action) {
switch(action.type) {
case 'add_todo': {
return [
...state,
action.payload.todo
]
}
default:
return state;
}
}
步骤 - 4
//todosAction.js
export const addTodo = (todo) => {
return({
type:'add_todo',
payload: {
todo
}
})
};
步骤 - 5
// index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import App from './App';
import store from '../store';
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
您可以避免自己选择文件路径。导入正确的文件路径。
步骤 - 5
// Todos.js
import React from 'react';
import { useDispatch, useSelector } from 'react-redux';
import {addTodo } from './todosActions';
const Todos = () => {
const { todos } = useSelector(state => state.todos);
const dispatch = useDispatch();
useEffect(() => {
console.log("todos", todos); // show all todos state
} ,[])
const todo = {
id: 1,
title: "redux is state management library"
}
const todoHandler = () => {
dispatch( addTodo(todo));
}
return(
<div>
// Todos Here
<button onClick={todoHandler}> add todo </button>
</div>
);
}