[我发现在渲染中使用'{Toolbar()}'时useContext(ThemeContext)的值未更新。
react渲染或差异与''和'{Toolbar()}'有什么区别?
这里是代码,您可以复制它并在沙盒中运行,谢谢!
这里是代码,您可以复制它并在沙盒中运行,谢谢!
这里是代码,您可以复制它并在沙盒中运行,谢谢!
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>
);
}
如果将其作为函数(ToolBar()
)调用,它实际上将返回其内容,因此不被视为React组件。如果使用<Toolbar />
,则它是组件,并且是使用它的正确方法。
简而言之,将其作为函数调用就像说“在此打印此函数返回的内容”,而将其用作<Toolbar /
就像说“在此处渲染此组件”。
该函数调用将导致状态,上下文或效果失败,因此,如果不将组件用作组件,则useContext
调用将不会达到预期的效果。
即使组件是functional组件,也不应将其直接用作函数。
React包含很多使useContext
和朋友工作的魔力,但是当不将该组件用作组件时,它无法这样做。如果您有兴趣进一步了解React背后的机制,以及为什么useContext
不起作用,请check this article。
在ReactJS中,您像这样调用组件:
<Component />
并且您这样调用函数:
{nameOfFunction()}
例如,如果有任何常量,则打印其值:
const[value, setValue] = useState("Some Text...");
...
{value} // would pring Some Text...
React.createElement(Toolbar, null)
Toolbar()
是函数调用。
Don't call function components. Render them.
这就是为什么在呈现组件时需要使用JSX(或React.createElement),而不是简单地调用该函数。 这样,可以将所有使用的钩子注册到React创建的组件的实例中。