假设我有一个 input
组件,它将通过其 onChange
处理程序更新状态。
function updateInputState(newvalue) {
return({
type: "UPDATE_INPUT_STATE",
payload: newValue
});
}
function InputComponent(props) {
function onChange(event) {
const newValue = event.target.value;
// OPTION #1 - WITHOUT AN ACTION CREATOR. DISPATCH THE ACTION DIRECTLY
dispatch({
type: "UPDATE_INPUT_STATE",
payload: newValue
});
// OPTION #2 - WITH AN ACTION CREATOR
dispatch(updateInputState(newValue));
}
return(
<input value={props.value} onChange={onchange}/>
);
}
我认为选项 #2 更具可读性,那么为什么我要使用操作创建器而不是常规操作调度?
最佳答案
主要优点是简单和易于维护,尤其是在 async actions 方面。 .
Action creators can also be asynchronous and have side-effects.
因此它简化了组件 View 中的使用:
// Lets say we suddenly want to make updateInputState async action
function InputComponent(props) {
function onChange(event) {
const newValue = event.target.value;
// Edit its action creator implementation
dispatch(updateInputState(newValue));
// on the other hand, without action creator, you need to
// change this code to async everywhere across the app
dispatch({
type: "UPDATE_INPUT_STATE",
payload: newValue,
});
}
return <input value={props.value} onChange={onchange} />;
}
Dave Ceddia在维护方面提出了这一重要观点:“当您在多个位置复制并粘贴一个操作时,更改会变得更加困难。”
Notice that writing action creators is more like "an old API" you should use
redux-toolkit
now (2020).
关于javascript - 在 Redux 中使用 Action 创建器的主要好处是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63806936/