gpt4 book ai didi

reactjs - react : useContext value is not updated in the nested function

转载 作者:行者123 更新时间:2023-12-03 19:41:17 29 4
gpt4 key购买 nike

我有一个简单的上下文,它设置了一些从后端获取的值,伪代码:

export const FooContext = createContext();

export function Foo(props) {
const [value, setValue] = useState(null);

useEffect(() => {
axios.get('/api/get-value').then((res) => {
const data = res.data;
setValue(data);
});
}, []);

return (
<FooContext.Provider value={[value]}>
{props.children}
</FooContext.Provider>
);
}

function App() {
return (
<div className="App">
<Foo>
<SomeView />
</Foo>
</div>
);
}

function SomeView() {
const [value] = useContext(FooContext);

console.log('1. value =', value);

const myFunction = () => {
console.log('2. value = ', value);
}

return (<div>SomeView</div>)
有时我得到:
1. value = 'x'
2. value = null
所以基本上由于某种原因,尽管被更新为 'x',但嵌套函数内的值仍然为空。 .

最佳答案

首先,如果没有值,您需要为您的上下文提供一些默认值,然后将默认值设置为 null。

export const FooContext = createContext(null);
大多数情况下,有两种方法可以在 Provider 组件中传递值。您可以通过 objecttuplevalue Provider 组件中的 Prop 。
我会给你一个例子,传递一个 object在提供者组件中。 @dna 给出了一个 tuple 的例子.
<FooContext.Provider value={{value,setValue}}>
{props.children}
</FooContext.Provider>
现在,如果您想在另一个组件中使用该值,您需要像这样解构对象
const {value, setValue} = useContext(FooContext);

如果您调用了嵌套的 myFunction()正确地如下所示,那么该值也将是 x而不是空。
function SomeView() {
const [value] = useContext(FooContext);

console.log('1. value =', value);

const myFunction = () => {
console.log('2. value = ', value);
}
SomeView.myFunction = myFunction; //updated line
return (<div>SomeView</div>)
}
<button onClick={SomeView.myFunction}>Click</myFunction>
输出 :
1. value = 'x'
2. value = ' x'

Now, the question is why it is returning a single character value instead of the state value.


在 Javascript 中,字符串是一个字符数组。
例如。
const string = ['s','t','r','i','n','g'];
//This is equivalent to
const string = "string";
在您的情况下,您的状态值可能是一个字符串。因此,当您解构字符串时,您将获得字符串的第一个字符。
举个例子你就明白了。

const string = "subrato";

const [str] = string;
console.log(str);

关于reactjs - react : useContext value is not updated in the nested function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64259890/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com