我一直在研究 react 和搜索,但没有找到任何答案。
所以我有这个组件调用我的 api 来知道在呈现它时要做什么。
问题是它被渲染了两次,我想知道这是否可以,因为我是在告诉组件自行更新,或者我是否做错了什么。
根据我的搜索,如果调用 setState,渲染就会运行,但我仍然觉得这有点奇怪,可能是因为我是 React 的新手,但我想把事情搞清楚。
例子:
class Car extends React.Component {
constructor() {
super();
this.state = {
color:'none',
};
}
componentDidMount(){
this.updateColor();
}
updateColor() {
this.setState(() => {
return { color: 'red'}
});
}
render() {
console.log("potatoes");
return (
<div>
<h1>Car color: {this.state.color}</h1>
</div>
);
}
}
React.render(<Car />, document.getElementById('app'));
代码笔链接:
https://codepen.io/jorgemdss/pen/qBEqroE?editors=0010
如果您打开开发工具,您会看到“potatoes”被记录了两次。
这是完全正常的还是我做错了什么?
最佳答案
这是完全正常的。
第一次渲染是在组件挂载时,第二次是在运行 componentDidMount
并调用 updateColor
时更新状态并再次渲染。
您可能看不到,但您的组件将呈现none
和 red
之后。
关于javascript - 组件渲染时 React 调用 api 运行两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59361867/