gpt4 book ai didi

reactjs - ComponentDidMount 与 ComponentWillMount?

转载 作者:行者123 更新时间:2023-12-03 14:15:09 24 4
gpt4 key购买 nike

我有一个关于何时 componentDidMount 以及何时触发的问题,我是使用 React 的新手,并且文档的示例很模糊。为什么我的组件没有触发?

var App = React.createClass({    
getInitialState: function() {
var events = ['initial state has been called'];
return {
events: events
}
},
componentWillMount: function() {
return {
mount: this.state.events.push('componentWillMount has been called')
}
},
componentDidMount: function() {
return
console.log('mounted!');
},
render: function() {
var eventMap = this.state.events.map(function(event, i) {
return <li key={i}>{event}</li>;
})
return (
<div>
<ul>
{eventMap}
</ul>
</div>
)
}
})

ReactDOM.render(
<App />,
document.getElementById('container')
)

最佳答案

您可能会问为什么您的 eventMap 不包含带有字符串 'componentWillMount has been called'li。这是因为您无法push项目到this.state。您必须调用 this.setState 这将导致您的 render 函数再次运行。

此外,还不清楚为什么要返回带有 mount 键的对象,因为 componentWillMount 不会将其结果传递给任何东西。

componentWillMount: function() {    
var events = this.state.events;
events.push('a new value')
this.setState({ events: events }); // important!
}

您可能还想知道为什么在您的 componentDidMount 函数中控制台消息没有出现。这是因为返回后不能换行:

componentDidMount: function() {    
return // magic semi-colon gets added here, nothing below will happen.
console.log('mounted!');
}

做正确的事情并将要返回的内容放在同一行(或使用括号)

componentDidMount: function() {    
return console.log('mounted!');
},

或者

componentDidMount: function() {    
return (
console.log('mounted!');
)
}

但是,正如相当粗鲁的 @zerkms 所指出的那样,从此函数返回任何内容是没有意义的。这只是指出了为什么你的 console.log 没有触发。

我发现这些有关组件生命周期的文档非常清晰,因此请保持打开状态:

https://facebook.github.io/react/docs/component-specs.html

关于reactjs - ComponentDidMount 与 ComponentWillMount?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35166691/

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