[英]React - Strict Mode off, functional component constructed second time after first state change only
I'm confused why function components (non class components don't confuse with functional) are constructed twice when state changes?我很困惑为什么 function 组件(非 class 组件不会与功能混淆)在 state 更改时构造两次?
My understanding was that the function is constructed once just like a class' component constructor?我的理解是 function 就像类的组件构造函数一样构造一次?
Note: React is NOT running in strict mode.注意: React 没有在严格模式下运行。
Sample code:示例代码:
index.js: index.js:
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, // notice no strict mode
rootElement
);
Eg 1: LogStatement called once - simple and obvious:例如 1: LogStatement 调用一次 - 简单明了:
function App1() {
console.log("App constructed");
return <div>Hello</div>;
}
Eg 2: LogStatement called twice - not quite obvious but maybe its due to setDidMount?例如 2: LogStatement 调用了两次 - 不是很明显,但可能是由于 setDidMount? :
:
function App2() {
console.log("App constructed");
const [didMount, setDidMount] = useState(false);
useEffect(() => {
setDidMount(true);
}, []);
return <div>Hello</div>;
}
Eg 3: LogStatement called twice.例如 3: LogStatement 调用了两次。 no matter how many independent state variables:
不管有多少个独立的 state 变量:
function App3() {
console.log("App constructed:" + i++);
const [didMount, setDidMount] = useState(false);
const [someState, setSomeState] = useState("empty");
useEffect(() => {
setDidMount(true);
}, []);
useEffect(() => {
setSomeState("full");
}, []);
return <div>Hello</div>;
}
Finally class component最后是 class 组件
Eg 4: LogStatement called once - as expected例如 4: LogStatement 调用一次 - 正如预期的那样
class App4 extends Component {
constructor() {
super();
this.state = {
didMount: false
};
console.log("App constructed:" + i++);
}
componentDidMount() {
this.setState({
didMount: true
});
}
render() {
return <div>Hello</div>;
}
}
My understanding was that the function is constructed once just like a class' component constructor?
我的理解是 function 就像类的组件构造函数一样构造一次?
It's not constructed at all, that's just a class thing.它根本没有构造,那只是 class 的东西。 Putting a log statement in the body of a function component is roughly equivalent to putting it in the
render
method of a class component.将日志语句放在 function 组件的主体中,大致相当于将其放在 class 组件的
render
方法中。 So your log is telling you how many times the component rendered.所以你的日志告诉你组件渲染了多少次。 Setting state causes rendering (usually), so by calling
setDidMount(true)
, you are rerendering the component.设置 state 会导致渲染(通常),因此通过调用
setDidMount(true)
,您正在重新渲染组件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.