【发布时间】:2017-03-17 16:04:34
【问题描述】:
我希望一个组件只调用一次方法,并且只在组件第一次被渲染时调用。我在constructor() 中尝试过它,认为它应该只发生一次,并且只在它第一次挂载时发生,但看起来每当再次渲染该组件时,constructor() 也会再次被调用。
有没有办法让组件只在第一次渲染时调用一个方法?
谢谢
【问题讨论】:
标签: javascript html css reactjs jsx
我希望一个组件只调用一次方法,并且只在组件第一次被渲染时调用。我在constructor() 中尝试过它,认为它应该只发生一次,并且只在它第一次挂载时发生,但看起来每当再次渲染该组件时,constructor() 也会再次被调用。
有没有办法让组件只在第一次渲染时调用一个方法?
谢谢
【问题讨论】:
标签: javascript html css reactjs jsx
componentWillMount() 被调用预渲染并且只有一次直到页面刷新。
https://facebook.github.io/react/docs/react-component.html#componentwillmount
componentDidMount() 在 render() 之后立即被调用,此时 DOM 可用。这只会在第一次加载时发生,直到页面刷新。
https://facebook.github.io/react/docs/react-component.html#componentdidmount
【讨论】:
componentDidMount() 在重新渲染时会再次调用它吗?我只希望它只被调用一次,并且只在第一次被调用,即使组件被重新渲染,也永远不会再被调用。
componentWillMount() 和 componentDidMount() 将再次被调用,对吗?但我只希望数据初始化仅在第一次安装时发生,以后再也不发生,即使在不同页面之间导航也是如此。
componentDidMount() 中拨打电话,并使用道具将数据向下传递给子组件。对于站点范围的数据,这两种方式都是完全可以接受的。
您可以在导航时使用 getDerivedStateFromProps 并传递一个空参数,这会在导航后触发一次该方法。
// caller
this.props.navigation.navigate('SOMEWHERE', {})
// SOMEWHERE
static getDerivedStateFromProps(nextProps, prevState){
doSomething()
return null
}
【讨论】:
您可以在首次加载页面时在 localStorage 中设置一个变量。然后,无论何时渲染,您只需获取并测试该变量:
async componentDidMount() {
...
if(localStorage.getItem('reRender') !== "true") {
//Processing to do only for the very first render
localStorage.setItem('reRender', "true");
}
}
您可以在之后根据您的用例(例如注销时)重置变量:
localStorage.removeItem('reRender');
【讨论】: