【发布时间】:2017-11-25 08:08:36
【问题描述】:
我有一个父组件,它有 1 个子组件。我通过道具传递数据来更新我的孩子。最初,它工作正常,但是当我单击一个按钮并使用 setState 更新状态时,在 setState 完成时,孩子将使用旧值呈现。我已经在孩子中使用 componentWillReceiveProps 解决了它,但这是正确的方法吗?
在下面的代码中,如果我在 filterResults 函数中设置状态,它不会更新 Emplist 组件。
import React, { Component } from 'react';
import {Search} from './search-bar'
import Emplist from './emplist'
class App extends Component {
constructor(props){
super(props);
this.emp=[{
name:'pawan',
age:12
},
{
name:'manish',
age : 11
}]
this.state={emp:this.emp};
this.filterResults=this.filterResults.bind(this);
}
filterResults(val)
{
if(this.state)
{
let filt=[];
filt.push(
this.emp.find(e=>{
return e.age==val
})
);
this.setState({emp:filt});
}
}
render() {
return (
<div className="App">
<Search filterResults={this.filterResults}/>
<Emplist emp={this.state.emp}/>
</div>
);
}
}
export default App;
EmpList Componet
import React,{Component} from 'react'
export default class Emp extends Component
{
constructor(props){
super(props);
this.emplist=this.props.emp.map(e=>{return <li>{e.name}</li>});
this.next=this.emplist;
}
componentWillReceiveProps(nextProps,nextState,prevProps,prevState,nextContext,prevContext){
// this.props.updated(this.props.empo);
this.next=nextProps.emp[0];
if(this.next)
this.emplist= nextProps.emp.map(e=>{return <li>{e.name}</li>});
}
render(){
if(!this.next)
return <div>name not found</div>
else
return (
<div>
<br/>
<p>The list is here</p>
<ul>
{this.emplist}
</ul>
</div>
)
}
}
【问题讨论】:
-
是的,这是正确的方法。如果您不需要将这些值用于某些复杂的事情或孩子的其他任何事情,您可以直接将它们与
this.props.someValue一起使用。 -
在孩子中,我使用了 nextProps,因为当孩子渲染时我无法获得更新的道具。 this.props.someValue 将如何在 child 中工作?
-
你能给出你的子组件的完整代码吗?这将很容易。请使用代码更新您的问题。
-
使用 Redux 会很有帮助并且没有压力。当您有多个路线时,传统的参数传递方法有时会很忙。
-
@pKay 给出了答案。请检查。
标签: javascript reactjs redux