如何从ajax调用请求的父数据传递给子组件? 例如,我有这样的代码
class Parent extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
async componentDidMount() {
const response = await fetch();
this.setState(response.data);
}
render() {
return (
<ChildComponent data={this.state} /> // data={}
);
}
}
这里的问题是在获取数据之前,将挂载ChildComponent,因此我将在ChildComponent中获取空对象数据。
答案 0 :(得分:0)
检查数据是否可用
class Parent extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
async componentDidMount() {
const response = await fetch();
this.setState(response.data);
}
render() { // Return if response is Object
return Object.keys(this.state).length > 0
? <ChildComponent data={this.state} /> // data={}
: <div>Loading...</div>
}
render() { // Return if response is Array
return this.state.length > 0
? <ChildComponent data={this.state} /> // data={}
: <div>Loading...</div>
}
}
答案 1 :(得分:0)
仅当有一些数据时,您才可以决定渲染子代。 为此,也许不要用数据替换整个状态,而是创建一个单独的键。如果以后需要添加其他状态,将会更容易。
class Parent extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
async componentDidMount() {
const response = await fetch();
this.setState({ data: response.data });
}
render() {
const { data } = this.state;
return data ? <ChildComponent data={data} /> : null;
}
}