在React和Redux中,Reducer是一个纯函数,用于处理应用程序状态的更新。当你的Reducer无法接收到你的操作时,可能有以下几个原因:
import { createStore } from 'redux';
import rootReducer from './reducers';
const store = createStore(rootReducer);
// 操作类型
const ADD_TODO = 'ADD_TODO';
// 操作创建函数
function addTodoAction(todo) {
return {
type: ADD_TODO,
payload: todo
};
}
// Reducer
function todosReducer(state = [], action) {
switch (action.type) {
case ADD_TODO:
return [...state, action.payload];
default:
return state;
}
}
import { useDispatch } from 'react-redux';
import { addTodoAction } from './actions';
function TodoForm() {
const dispatch = useDispatch();
const handleSubmit = (e) => {
e.preventDefault();
const todo = e.target.todo.value;
dispatch(addTodoAction(todo));
e.target.todo.value = '';
};
return (
<form onSubmit={handleSubmit}>
<input type="text" name="todo" />
<button type="submit">Add Todo</button>
</form>
);
}
import { connect } from 'react-redux';
function TodoList({ todos }) {
return (
<ul>
{todos.map((todo, index) => (
<li key={index}>{todo}</li>
))}
</ul>
);
}
const mapStateToProps = (state) => ({
todos: state.todos
});
export default connect(mapStateToProps)(TodoList);
以上是一些可能导致Reducer无法接收操作的常见原因。通过检查这些方面,你应该能够解决你的问题并使Reducer能够正确地接收操作并更新应用程序的状态。如果你需要更多关于React和Redux的信息,可以参考腾讯云的React和Redux相关产品和文档:
领取专属 10元无门槛券
手把手带您无忧上云