更新的React Context值没有反映在上一个屏幕中



我已经用A->B.

//TestContext.js
export const TestContext = createContext('initial value');
//B.js
const {myVal,changeMyVal} = useContext(TestContext);
return(
<View>
<Button
onPress={() => {
changeMyVal('new value')
console.log(myVal); // Prints 'new value'
}}>
</View>
);
//A.js
const {myVal} = useContext(TestContext);
return(
<View>
<Button
onPress={() => {
console.log(myVal); // Prints 'initial value'
}}>
</View>
);

当我从B返回到A并打印上下文值时,我仍然得到初始值。既然我从B回来时没有重新渲染,那么如何在A中获得更新的值?

useContext不会像useState钩子那样返回更新程序函数。如果你想从消费者那里更新你的状态,只需从提供者那里提供一个更新程序功能,比如

const ContextShared = createContext({ value: "", updater: () => null });
...
const [value, updater] = useState("initialValue");
...
<ContextShared.Provider value={{ value, updater }}>
<Component1 />
<Component2 />
</ContextShared.Provider>

function Component1() {
const { value } = useContext(ContextShared);
...
}

function Component2() {
const { updater } = useContext(ContextShared);
function handleClick() {
updater("updated from page 2");
}

return <div onClick={handleClick}>Page 2 </div>;
}

现场工作示例

最新更新