constructor(props) { super(props); this.state = { form:this.props.form }; } <p>{this.props.form.name}</p>为啥我这里子组件初始化通过pros获取父组件数据当我子组件调用父组件事件改变数据后 子组件的值name还能被改变 初始化方法不是只执行一次么当我有两个组件A 和 B A组件调用父组件方法 父组件数据改变触发B组件数据更新操作时 A组件按上面的写法 数据正常传递 B组件不行 B组件通过componentWillReceiveProps()方法才可更新数据 父组件class ComModal extends React.Component{ constructor(props) { super(props); this.state = { form:{ }, show:false }; } showChange(){ that.setState({ show:true }) } render(){ return( <div> <A cbclick={e=>that.showChange()}/> <B show={that.state.show}/> </div> ) } } A组件 class A extends React.Component{ 调用showChange() } B组件 class B extends React.Component{ constructor(props) { super(props); this.state = { show:this.props.show //这样的话A改变show后 render里不会改变 }; } componentWillReceiveProps(nextProps){ 这里可以 } render(){ return ( <p>{that.state.show?'展示':'隐藏'}</p> ) } }
4 回答
茅侃侃
TA贡献1842条经验 获得超22个赞
React有三个阶段:挂载、更新和卸载。
挂载的声明周期主要有:
constructor
render
componentDidMount
其中constructor里把父组件传递的props绑定到子组件的this上。
如果调用父组件传递的回调函数来改变数据,那么父组件传递的props会出现变化
此时触发子组件的更新阶段:
componentWillReceiveProps
shouldComponentUpdate
render
componentDidUpdate。
当我子组件调用父组件事件改变数据后 子组件的值name还能被改变
我对你说的这句话里的改变,理解是页面中展示的数据变了。而控制页面展示变化的是render生命周期,上文中可以看到不管是挂载还是更新,都会触发render。
添加回答
举报
0/150
提交
取消
