这条线的调度来自哪里? export const setAlert = (msg, alertType,timeout=5000) => dispatch =>
where is dispatch coming from in this line? export const setAlert = (msg, alertType,timeout=5000) =>dispatch =>
我看到了这段代码。 He/she 正在为 react-redux 应用中的 redux 创建一个动作。我不明白 dispatch 是从哪里来的。你能解释一下这也是一个好习惯吗?
import uuid from 'uuid';
import {SET_ALERT,REMOVE_ALERT} from './types';
export const setAlert = (msg, alertType,timeout=5000) =>dispatch =>{
const id = uuid.v4();
dispatch ({
type:SET_ALERT,
payload:{msg,
alertType,
id}
});
setTimeout(()=>dispatch({type:REMOVE_ALERT,payload:id}),timeout)}
我猜它正在使用 redux-thunk,它充当中间件。 setAlert returns 函数,该函数以调度作为该函数的第一个参数调用。如果您稍微清理一下,可能会更有助于理解
export const setAlert = (msg, alertType,timeout=5000) => {
const id = uuid.v4();
return (dispatch) => {
dispatch ({
type:SET_ALERT,
payload:{
msg,
alertType,
id
}
});
};
我通常在需要在操作中使用异步函数的情况下使用它,例如 ajax 请求。
它来自 mapDispatchToProps
:
// action
export const action = (params) => async (dispatch) => // it can be async btw
actionCodeHere()
// component
import {action as importedAction} from 'action'
const component = ({action}) => {
React.useEffect(() => { action(params) }, [])
return <div/>
}
const mapDispatchToProps = {
action: importedAction
} // just object
export default connect(null, mapDispatchToProps)(component)
这是好的做法吗?
我认为它比我看到的许多其他方式(尤其是 redux saga,毫无意义和无情)更好,它比 mapDispatchToProps 是一个函数时代码更少。
更简单的方法是直接在操作文件中从存储中导入 dispatch
而根本不使用 mapDispatchToProps
,但我从未见过这种方法,这似乎不是一个好习惯。
我看到了这段代码。 He/she 正在为 react-redux 应用中的 redux 创建一个动作。我不明白 dispatch 是从哪里来的。你能解释一下这也是一个好习惯吗?
import uuid from 'uuid';
import {SET_ALERT,REMOVE_ALERT} from './types';
export const setAlert = (msg, alertType,timeout=5000) =>dispatch =>{
const id = uuid.v4();
dispatch ({
type:SET_ALERT,
payload:{msg,
alertType,
id}
});
setTimeout(()=>dispatch({type:REMOVE_ALERT,payload:id}),timeout)}
我猜它正在使用 redux-thunk,它充当中间件。 setAlert returns 函数,该函数以调度作为该函数的第一个参数调用。如果您稍微清理一下,可能会更有助于理解
export const setAlert = (msg, alertType,timeout=5000) => {
const id = uuid.v4();
return (dispatch) => {
dispatch ({
type:SET_ALERT,
payload:{
msg,
alertType,
id
}
});
};
我通常在需要在操作中使用异步函数的情况下使用它,例如 ajax 请求。
它来自 mapDispatchToProps
:
// action
export const action = (params) => async (dispatch) => // it can be async btw
actionCodeHere()
// component
import {action as importedAction} from 'action'
const component = ({action}) => {
React.useEffect(() => { action(params) }, [])
return <div/>
}
const mapDispatchToProps = {
action: importedAction
} // just object
export default connect(null, mapDispatchToProps)(component)
这是好的做法吗?
我认为它比我看到的许多其他方式(尤其是 redux saga,毫无意义和无情)更好,它比 mapDispatchToProps 是一个函数时代码更少。
更简单的方法是直接在操作文件中从存储中导入 dispatch
而根本不使用 mapDispatchToProps
,但我从未见过这种方法,这似乎不是一个好习惯。