React中从Context获取的函数在自定义异步方法中不生效如何解决
问题原因
错误写法中仅引用了helloWorld函数对象,没有执行函数本身:await helloWorld只是拿到了函数的引用地址,不会触发内部的console.log逻辑。同时你当前定义的helloWorld是同步函数,不需要搭配await使用。
修复方案
方案1:保持helloWorld为同步函数,直接调用即可
const { helloWorld } = useTestContext() const handleHelloWorld = async () => { // 这里可以放你需要先执行的其他异步逻辑 helloWorld() // 加括号执行函数 } // 绑定点击事件时不要漏了调用handleHelloWorld return <button onClick={handleHelloWorld} />
如果handleHelloWorld内没有其他异步逻辑,可以去掉async关键字简化写法:
const handleHelloWorld = () => { helloWorld() }
方案2:如果helloWorld后续需要改造为异步函数,调用后再await
先修改Provider内的函数定义:
export const TestProvider = () => { const helloWorld = async () => { // 可在此处添加异步请求等逻辑 console.log('hello world'); }; return ( <TestContext.Provider value={{ helloWorld }}> ) }
调用时加括号执行后再await:
const handleHelloWorld = async () => { await helloWorld() }
内容的提问来源于stack exchange,提问作者k10a
相关产品推荐
相关产品推荐

