gpt4 book ai didi

javascript - 如何修复 : Context Provider not passing new context values down to children

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:10:31 26 4
gpt4 key购买 nike

我是 React Hooks 和 React Context 的新手,我想知道为什么我的 Context Provider 似乎没有将新值传递给子组件。我将其设置为初始值“ColorContext”为“红色”,但我希望按钮中“ColorContext”的值为“绿色”。但是,当我尝试这样做时,“ColorContext”值不会改变并保持“红色”。

这是我的代码的链接: https://stackblitz.com/edit/react-8mhqwu

import React, { Component, useState, useContext, createContext } from 'react';
import { render } from 'react-dom';

const ColorContext = createContext('red')


const App = (props) => {

return (
<div className="app">
<ColorContext.Provider value= {'green'}>
<button
style = {{backgroundColor: useContext(ColorContext)}}
>
Click here
</button>
</ColorContext.Provider>
</div>
)
}

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

最佳答案

参见 Hook Rules :

Only Call Hooks at the Top Level

Don’t call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function. By following this rule, you ensure that Hooks are called in the same order each time a component renders.

因此,将使用 useContext Hook 的新消费组件作为一个好习惯。

const ColorContext = createContext('red');

const Button = () => {
const value = useContext(ColorContext);
return (
<button style = {{backgroundColor: value}}
>
{value}
</button>
);
};

const App = (props) => {
return (
<div className="app">
<ColorContext.Provider value={'blue'}>
<Button />
</ColorContext.Provider>
</div>
)
};

关于javascript - 如何修复 : Context Provider not passing new context values down to children,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57193399/

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