gpt4 book ai didi

javascript - 在 React 中将多个值和 setter 对传递给 Context.Provider

转载 作者:行者123 更新时间:2023-12-03 13:35:17 26 4
gpt4 key购买 nike

到目前为止我找到的所有文档和博客文章都只涉及单个 [value, setValue] 对场景。就我而言,我希望/需要使用 useContext Hook 将多对 [value, setValue] 变量传递给 Provider。

这是我在 CodePen 中设置的典型示例: https://codepen.io/nardove/pen/XWrZRoE?editors=0011

const App = () => {
return(
<div>
<MyProvider>
<ComponentA />
</MyProvider>
</div>
);
}

const MyContext = React.createContext();
const MyProvider = (props) => {
const [value, setValue] = React.useState("foo");
return(
<MyContext.Provider value={[value, setValue]}>
{props.children}
</MyContext.Provider>
);
}

const ComponentA = () => {
const [value, setValue] = React.useContext(MyContext);
return(
<div>
<h1>
The value is: {value}
</h1>
</div>
);
}

ReactDOM.render(<App /> , document.getElementById('app'));

如果您可以分享有关如何将多个 [value, setValue] 对传递给提供者的任何想法或解决我的问题的替代方案,我们将不胜感激

最佳答案

Context.Provider接受任何值,因此您可以尝试传递一个对象:

<MyContext.Provider
value={{ value: [value, setValue], value2: [value2, setValue2] }}
>
{props.children}
</MyContext.Provider>;
const App = () => {
return (
<MyProvider>
<ComponentA />
</MyProvider>
);
};

const MyContext = React.createContext();

const MyProvider = props => {
const [value, setValue] = React.useState("foo");
const [value2, setValue2] = React.useState("goo");

return (
<MyContext.Provider
value={{ value: [value, setValue], value2: [value2, setValue2] }}
>
{props.children}
</MyContext.Provider>
);
};

const ComponentA = () => {
const { value, value2 } = React.useContext(MyContext);
const [stateValue, setStateValue] = value;
const [stateValue2, setStateValue2] = value2;

return (
<div>
<h1>The value is: {stateValue}</h1>
<h1>The value2 is: {stateValue2}</h1>
</div>
);
};

ReactDOM.render(<App />, document.getElementById("app"));
<小时/>

请注意,在尝试优化无用渲染时有一个警告(确保您不仅仅是 optimizing prematurely ):有 no render bailout for Context Consumers .

As for v17, may be change in near future.

关于javascript - 在 React 中将多个值和 setter 对传递给 Context.Provider,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57840535/

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