在 Redux 中使用 action creator 的主要好处是什么?
What is the main benefit of using action creators in Redux?
假设我有一个 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 更具可读性,那么为什么我要使用 action creator 而不是常规的 action dispatch?
主要优点是简单易维护,尤其是 async actions。
Action creators can also be asynchronous and have side-effects.
因此简化了在组件视图中的使用:
// 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} />;
}
Notice that writing action creators is more like "an old API" you should use redux-toolkit
now (2020).
假设我有一个 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 更具可读性,那么为什么我要使用 action creator 而不是常规的 action dispatch?
主要优点是简单易维护,尤其是 async actions。
Action creators can also be asynchronous and have side-effects.
因此简化了在组件视图中的使用:
// 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} />;
}
Notice that writing action creators is more like "an old API" you should use
redux-toolkit
now (2020).