我有一个名为App
的父组件。它保持状态和改变状态的形式。
我删除了不重要的代码。当我在表单中键入内容时,state.item
中会添加一个对象项,但ToCompleteItemsComponent
不会更新。有没有办法在状态更改
class App extends Component {
state = {
items: []
}
submitItem=(e)=> {
e.preventDefault();
let items = this.state.items;
items.push({
name: this.state.ValuePlaceholder,
completed: false
});
this.setState({
items
});
}
render() {
return (<BrowserRouter>
<div className="wrap">
...
<form onSubmit={this.submitItem}>
<input type="text" />
</form>
<Route exact path="/"
render={props => <ToCompleteItemsComponent
items={this.state.items} /> }
/>
</div>
</BrowserRouter>
);
}
}
修改这是组件
class ToCompleteItemsComponent extends Component {
componentWillReceiveProps(nextProps) {
// check this.props vs nextProps and setState!
// do whatever you want.
console.log(nextProps)
}
render(){
return(<div>
<ul className="items">
{
this.props.items.map( (item,id)=> <li key={id}>{item.name} <span>x</span></li>)
}
</ul>
</div>)
}
}
export default ToCompleteItemsComponent;
console.log(nextProps)
返回一个空数组
答案 0 :(得分:0)
当父状态更新时,您可以使用: componentWillReceiveProps
ToCompleteItemsComponent 中的可以执行此操作:
在安装的组件之前调用componentWillReceiveProps() 收到新的道具。如果您需要更新状态以响应 prop更改(例如,重置它),您可以比较this.props 和nextProps并使用this.setState()执行状态转换 这种方法。
componentWillReceiveProps(nextProps) {
// check this.props vs nextProps and setState!
// do whatever you want.
}
正如您在此代码段中所看到的,console.log按预期工作。我重写了你在items数组中添加东西的方式。请注意,我从路由中删除了完全属性,因为在代码段中我无法正确使用路由器与路由器。
class App extends React.Component {
state = {
items: []
}
submitItem=(e)=> {
e.preventDefault();
this.setState({
items: this.state.items.concat([{
name: this.state.ValuePlaceholder,
completed: false
}])
});
}
render() {
return (<ReactRouterDOM.BrowserRouter>
<div className="wrap">
<form onSubmit={this.submitItem}>
<input type="text" />
<button type="submit">submit</button>
</form>
<ReactRouterDOM.Route path="/"
render={props => <ToCompleteItemsComponent
items={this.state.items} /> }
/>
</div>
</ReactRouterDOM.BrowserRouter>
);
}
}
class ToCompleteItemsComponent extends React.Component {
componentWillReceiveProps(nextProps) {
// check this.props vs nextProps and setState!
// do whatever you want.
console.log("HALO", this.props, nextProps)
}
render(){
return(
<div>
<ul className="items">
{
this.props.items.map( (item,id)=> <li key={id}>{item.name} <span>x</span></li>)
}
</ul>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://unpkg.com/react-router/umd/react-router.min.js"></script>
<script src="https://unpkg.com/react-router-dom/umd/react-router-dom.min.js"></script>
<div id="root"></div>