[英]React Child components in an Array not updating on prop change
我想使用從父組件狀態傳遞過來的prop更新數組中的所有子組件。 基本示例如下所示。 數組中的每個子組件都是無狀態的,並且具有由父組件的狀態確定的prop值。 但是,當父組件狀態更改時,子組件不會隨更改重新呈現。 當父母的狀態發生變化時,我該如何重新渲染子組件? 謝謝!
import React from 'react';
import ReactDOM from 'react-dom';
class Child extends React.Component {
render(){
return (
<p>
<button onClick = {(e) => this.props.onClick(e)}>
click me
</button>
{this.props.test}
</p>
)
};
}
class Parent extends React.Component{
constructor(props){
super(props);
this.state = {msg: 'hello', child_array: []};
this.handleClick = this.handleClick.bind(this);
}
handleClick(e){
e.preventDefault();
const msg = this.state.msg == 'hello' ? 'bye' : 'hello';
this.setState({msg: msg});
}
componentDidMount(){
let store = [];
for (var i = 0; i < 5; i++){
store.push(<Child test = {this.state.msg} key = {i} onClick = {this.handleClick}/>);
}
this.setState({child_array: store});
}
render(){
return(
<div>
{this.state.child_array}
</div>
)
}
}
ReactDOM.render(<Parent />, document.getElementById('root'));
問題在於您正在父級的componentDidMount()
方法中渲染子級組件(並由此this.state.msg
的值進行this.state.msg
)。 您需要改為使用父級的render()
方法來渲染它們。
如評論中所述
它不會再次重新渲染,因為您正在componentDidMount中生成Chil組件,並且第一次渲染后,每個組件僅對該方法調用一次。 因此,當您的回調觸發時,child_array將為空
相反,您可以執行的操作是刪除componentDidMount方法代碼,然后在render中進行操作,如下所示。 在以下情況下,每次onclick在子組件中觸發時,它將呈現
render(){
const store = [];
for (var i = 0; i < 5; i++){
store.push(<Child test = {this.state.msg} key = {i} onClick = {this.handleClick}/>);
}
return(
<div>
{store}
</div>
)
componentWillReceiveProps將在您的情況下工作,每次您獲得道具時,子組件都會重新渲染。
class Child extends React.Component {
constructor(props) {
super(props);
let initialData = (
<p>
<button onClick = {(e) => self.props.onClick(e)}>
click me
</button>
{nextProps.test}
</p>
);
this.state = {data: initialData };
}
componentWillReceiveProps(nextProps) {
let self = this;
let updatedHtml = (
<p>
<button onClick = {(e) => self.props.onClick(e)}>
click me
</button>
{nextProps.test}
</p>
);
this.setState({data: updatedHtml})
}
render(){
return (
{data}
)
};
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.