gpt4 book ai didi

reactjs - 更新后的状态未在子组件中呈现

转载 作者:行者123 更新时间:2023-12-03 14:25:04 25 4
gpt4 key购买 nike

我正在尝试从 NASA 的 API 中提取一张图片来获取他们当天的天文图片。当我更新 API 调用和 console.log this.state.picture 中的状态时,我可以看到该图片已设置为数据对象。但是当我尝试在渲染中记录图片时,它会记录一个空数组。我在以前的作业中使用了类似的方法,但从未遇到过这个问题,所以我真的不知道我做错了什么。我是 React 新手,如果答案真的很明显,我很抱歉。

父组件:

class App extends Component {
state = {
picture: [],
asteroids: [],
}

render() {
return (
<div className="App">
<Route exact path="/" component={Homepage}/>

<Route path="/apod" render={() =>
<APOD picture={this.state.picture}/>}/>

<Route path="/asteroids" render={() =>
<Asteroids asteroids={this.state.asteroids} />} />
</div>
);
}
}

export default App;

子组件:

class Apod extends React.Component{
getApodPicture = e => {
e.preventDefault();

let url = `https://api.nasa.gov/planetary/apod?api_key=v1sEi9chxFYzrf1uXei0J1GvXaemhnQXiDjEcnK2`;
fetch(url)
.then(res => {
if (!res.ok){
throw new Error (res.status)
}
return res.json();
})
.then(data => {
this.setState({picture: data})
console.log(this.state.picture) // logs the data object from NASA
})
.catch(err => console.log(err))
}

render(){
console.log(this.props.picture) // logs []
// console.log(this.state.picture) // returns "Cannot read property 'picture' of null"
return(
<div>
<h1>Astronomy picture of the day!</h1>
<Link to="/">Back to homepage</Link>

<section>
<button onClick={e => this.getApodPicture(e)}>Click to see picture</button>
</section>
</div>
)
}
}

export default Apod;

最佳答案

This.setState 将设置组件的状态,而不是父组件的状态。

您将需要一个changeHandler来获得所需的结果。

类似的东西


class App extends Component {
state = {
picture: '',
asteroids: [],
}

pictureChangeHandler = value => {
this.setState(value);
}

render() {
return (
<div className="App">
<Route exact path="/" component={Homepage}/>

<Route path="/apod" render={() =>
<APOD pictureChangeHandler={this.pictureChangeHandler}
picture={this.state.picture}/>}/>

<Route path="/asteroids" render={() =>
<Asteroids asteroids={this.state.asteroids} />} />
</div>
);
}
}

export default App;

class Apod extends React.Component{
getApodPicture = e => {
e.preventDefault();

let url = `https://api.nasa.gov/planetary/apod?api_key=v1sEi9chxFYzrf1uXei0J1GvXaemhnQXiDjEcnK2`;
fetch(url)
.then(res => {
if (!res.ok){
throw new Error (res.status)
}
return res.json();
})
.then(data => {
this.props.pictureChangeHandler(data)

})
.catch(err => console.log(err))
}

render(){
console.log(this.props.picture) // logs []
// console.log(this.state.picture) // returns "Cannot read property 'picture' of null"
return(
<div>
<h1>Astronomy picture of the day!</h1>
<Link to="/">Back to homepage</Link>

<section>
<button onClick={e => this.getApodPicture(e)}>Click to see picture</button>
</section>
</div>
)
}
}


关于reactjs - 更新后的状态未在子组件中呈现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55583785/

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