componentDidMount()为什么当我尝试再次调用该组件时它可能无法在 React 容器中工作?
有一个链接列表,例如
<Link key={element.name} to={'elements/:element'}} />
我从链接中获取此元素的名称并将其传递给 props 中的 ElementDetail 容器(有条件地)
<ElementDetail name={:element} />
name从props我已经使用内部方法componentDidMount():
@connect(
state => ({ element: state.element }),
dispatch => ({elementActions: bindActionCreators(elementActions, dispatch)})
)
export default class ElementDetail extends React.Component {
componentDidMount() {
console.log('>>> CDM')
let { getProperties } = this.props.elementActions;
getProperties(this.props.name)
}
render() {
let { properties, isLoading } = this.props.element;
let propertyGroups = properties['properties'];
console.log('>>> RENDER')
return <div />
首次安装组件时,代码按预期工作。
但是,当我尝试通过 Link 使用不同的数据再次调用 c 组件时,我只会在浏览器和props.name. 只有 render() 中的代码有效,我可以从控制台输出中看到这一点。我在哪里犯了错误?
没有完整的代码不好说,但是很明显这个组件不是在第二次初始化,而是在更新。这可以签入
componentWillReceiveProps()。如果第二次调用componentWillReceiveProps()而不是componentDidMount(),那么您需要使用componentWillReceiveProps()。事实是,当发送新
props的时,组件不会重新初始化,而只会接收新的props。找到了两个解决方案。
首先,我向组件添加了一个键属性,键发生了变化(我从路由中获取),这导致重新挂载组件的反应
每次更改键调用 ComponentDidMount()
其次是使用 componentWillReceiveProps() (感谢Nick的提示)
在组件本身
但是第二种方法有更多的代码并且是重复的。
如果有人给出他们的解释和评论,那就太好了。