[英]How to avoid rerender all child components which in loop when parent component state update
[英]How to make an http call in parent component to setState and then send the state to all child components?
所以我試圖從父級的 componentDidMount() 撥打 axios.get('{link here}') :
class Parent extends React.Component {
constructor(){
super();
this.state = {
stuff: []
}
}
componentDidMount() {
axios.get({link})
.then(res => {
this.setState({stuff: res.data})
}
}
render() {
return(
<Child stuff={this.state.stuff} />
)
}
然后是 Child 各種子組件,其中一個是這樣的:
class Child extends React.Component {
constructor(props) {
super(props);
}
render() {
return(
//To access everything in the data of parent here in child component
)
}
即使父母在 console.log() 中顯示數據,孩子也沒有收到任何東西
在 class Child
中,您可以訪問使用this.props
傳遞的道具。 它看起來像這樣:
class Parent extends React.Component { state = { name: 'Felix' } render() { return ( <Child name={this.state.name} /> ) } } class Child extends React.Component { render() { return <p>My Name is {this.props.name}</p> } } ReactDOM.render(<Parent />, document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="root"></div>
如果子組件不打算保存內部 state,那么您可以將其重構為功能組件:
function Child(props) {
return <p>My Name is {props.name}</p>
}
有關 function 和 class 組件的更多信息在這里。
不確定這是否是整個解決方案,但更換
constructor(){
super();
this.state = {
stuff=[]
}
}
經過
constructor(){
super();
this.state = {
stuff: []
}
}
您在 object 聲明中有一個=
符號。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.