如何实现带参数的Redux异步Action Creator并正确调度?
Redux异步Action Creator参数传递问题解决
问题场景
原本正常运行的Redux异步Action Creator,需要修改为支持接收动态参数userInput来拼接API请求地址。尝试将参数放到返回的async函数参数列表(与dispatch并列)时,打印userInput得到的是函数而非预期的'AAPL',需修正参数传递逻辑。
正确实现代码
修改后的Action Creator(ChartHandlePureFunc.js)
export function getBasic(userInput) { return async (dispatch) => { const response = await axios.get(`https://financialmodelingprep.com/api/v3/historical-price-full/${userInput}?apikey=*********`); dispatch(changeValue(response.data)); }; }
组件中调度调用(ChartHandler.js)
useEffect(() => { if (!req) { dispatch(getBasic('AAPL')); } }, [req]);
错误原因说明
如果把userInput写到返回的async函数参数里(比如return async (dispatch, userInput) => {...}),属于逻辑错误:Redux Thunk中间件只会给这个异步函数传入dispatch和getState两个固定参数,额外添加的userInput会被赋值为getState函数,自然无法得到预期的字符串。
正确的做法是将参数放在外层的Action Creator函数(getBasic)的参数列表中,调用getBasic('AAPL')时参数会被闭包保留,内部的异步函数可以直接访问该值。
内容的提问来源于stack exchange,提问作者Caleb
相关产品推荐
相关产品推荐

