gpt4 book ai didi

javascript - 将更新的状态作为 Prop 传递

转载 作者:搜寻专家 更新时间:2023-11-01 05:04:07 26 4
gpt4 key购买 nike

我是 React 的新手,想知道如果可能的话您是否可以看看这个问题。我在单击事件时对 API 进行 ajax 调用,并将结果存储在 'SearchButtons' 组件的状态中。

然后通过 props 将状态传递给子组件。然而,子组件 (SearchForm) 中的 props 等于父组件上的先前状态,并且在用户单击其中一个按钮时不会更新。

我想知道是否有办法解决这个问题,也许是在将 props 发送到子组件之前更新组件?

import React from 'react';
import SearchForm from './SearchForm'

class SearchButtons extends React.Component {
constructor(){
super();
this.state = {
data: {}
}
}

update(event){
$.ajax({
url: 'http://example/api/' + event.target.value,
dataType: 'json',
cache: false,
success: function(data) {
this.setState({ data: data })
}.bind(this)
});
}

render() {
return (
<div>
<button type="button" value="people" onClick={this.update.bind(this)} className="btn btn-primary">People</button>
<button type="button" value="car" onClick={this.update.bind(this)} className="btn btn-primary">Car</button>
<button type="button" value="planet" onClick={this.update.bind(this)} className="btn btn-primary">Planet</button>
<SearchForm data={this.state.data} />
</div>
)
}
}

export default SearchButtons

请参阅下面的 SearchForm 组件示例

import React from 'react';

class SearchForm extends React.Component {

componentWillReceiveProps(){
console.log(this.props.data);
}

render(){
return (
<form className="form-inline">
<div className="form-group">
<label className="sr-only" for="exampleInputEmail3"></label>
<input type="text" className="form-control" placeholder="Enter text..." />
</div>
<button type="submit" className="btn btn-default">Search</button>
</form>
)
}
}

export default SearchForm

最佳答案

componentWillReceiveProps 接收 next props 作为第一个参数,所以通过记录 this.state.props 你会看到 current Prop ,而不是正在收到的 Prop 。

尝试像这样记录下一个:

componentWillReceiveProps(nextProps){
console.log(nextProps.data);
}

当然,您还可以通过调用 componentDidUpdate 生命周期方法而不是(或同时调用,如果您想要监控这两个步骤)componentWillReceiveProps:

componentDidUpdate(prevProps, prevState) {
console.log(this.props.data);
}

看看 lifecycle methods如果你想了解更多!

关于javascript - 将更新的状态作为 Prop 传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37058533/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com