我发现在呈现中使用'{ Toolbar() }‘时,useContext(ThemeContext)的值不是更新的。
“”和“{ Toolbar() }”在react、render或diff中有什么区别?
import React, { useContext, useState } from "react";
import "./styles.css";
const themes = {
light: {
name: "light",
foreground: "black",
background: "white"
},
dark: {
name: "dark",
foreground: "white",
background: "black"
}
};
const ThemeContext = React.createContext(null);
const Toolbar = props => {
const theme = useContext(ThemeContext) || {};
console.log(`Toolbar theme`, theme);
return (
<div
style={{
height: 60,
backgroundColor: theme.background,
color: theme.foreground
}}
>
<div>{theme.name}</div>
</div>
);
};
export default function App() {
const [currentTheme, setCurrentTheme] = useState(themes.light);
const toggleTheme = theme => {
setCurrentTheme(theme);
};
console.log(`currentTheme`, currentTheme);
return (
<div className="App">
<ThemeContext.Provider value={currentTheme}>
<div>
<button onClick={() => toggleTheme(themes.light)}>light</button>
<button onClick={() => toggleTheme(themes.dark)}>dark</button>
</div>
{/* Toolbar() */}
{/* {Toolbar()} */}
<Toolbar />
</ThemeContext.Provider>
</div>
);
}发布于 2020-03-09 10:34:26
如果您调用它为一个函数(ToolBar()),它本质上返回它的内容,而不是这样的一个function组件。如果您使用<Toolbar />,那么它就是一个组件,也是正确的使用方法。
简而言之,将它作为一个函数调用就像说“在这里打印这个函数返回的东西”,使用它作为<Toolbar /就像说“在这里呈现这个组件”。
函数调用将导致状态、上下文或效果失败,因此如果不将组件用作组件,则useContext调用将不会产生预期的效果。
即使一个组件是一个功能组件,它也不应该直接用作一个函数。
React包含了很多让useContext和朋友工作的魔力,但是当组件没有被用作组件时,它就不能这么做了。如果您有兴趣了解更多关于反应背后的机制,以及为什么useContext不能工作的话,检查这篇文章。
发布于 2020-03-09 10:40:35
在ReactJS中,您可以像这样调用组件:
<Component />你这样称呼函数:
{nameOfFunction()}例如,如果有任何常量,则打印其值:
const[value, setValue] = useState("Some Text...");..。
{value} // would pring Some Text...发布于 2020-03-09 10:41:27
React.createElement(Toolbar, null)而Toolbar()是一个函数调用。
这就是为什么在呈现组件时需要使用JSX (或React.createElement),而不是简单地调用函数。通过这种方式,任何使用的钩子都可以在响应创建.的组件的实例中注册。
在您的示例中,useContext在调用博客文章中引用的Toolbar()时不会注册到组件的实例。
https://stackoverflow.com/questions/60598616
复制相似问题