我想将道具从孩子传递给父母。我在子类中从API请求获取数据,但是当我使用回调将它传递给Parent类时,它会向我发送空数组,尽管当我在Child类中检查它时它已满。我找不到问题所在。有什么建议? 注意:我在fetch()中使用回调。然后阻止
这是父类
class Parent extends React.Component {
constructor(props) {
super(props);
this.state = {
listDataFromChild: null
};
this.getData = this.getData.bind(this);
}
getData(val){
this.setState({listDataFromChild: val});
console.log(val.length);
}
render() {
return (
<div className="row">
<div className="col-md-2">
<TableSearchForm callbackFromParent = {this.getData}/>
</div>
<div className="col-md-8">
<Table data = {this.state.listDataFromChild}/>
</div>
</div>
)
}
这是Child类:
class Child extends React.Component {
constructor(props) {
super(props);
this.props = props;
this.state = { value: '' };
this.state = {data: []};
this.makeRequest = this.makeRequest.bind(this);
}
makeRequest() {
var apirequest = fetch(API_URL , {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
arg1: 'val1',
arg2: 'val2'
})
}).then(function(response){
return response.json() })
.then( function (json) {
result = json[0]["col1"];
var length = result.length
console.log("length is: " + length);
.then(this.props.callbackFromParent(result));
}
答案 0 :(得分:1)
下面
.then(this.props.callbackFromParent(result));
then
期望一个函数,但是你在then
内调用函数,这意味着你将该函数的返回值传递给then
。所以将函数传递给then
而不是像这样
.then(function(response){
return response.json()
}).then( function (json) {
result = json[0]["col1"];
return result;
}).then((result) => {
this.props.callbackFromParent(result)
});
答案 1 :(得分:0)
最好这样做
constructor(props) {
super(props);
this.props = props;
this.state = {
data: [] ,
value:[]
};
this.makeRequest = this.makeRequest.bind(this);
}
代替此
constructor(props) {
super(props);
this.props = props;
this.state = { value: '' };
this.state = {data: []};
this.makeRequest = this.makeRequest.bind(this);
}