gpt4 book ai didi

javascript - React 无法读取未定义的属性 'length' 但数组已定义

转载 作者:行者123 更新时间:2023-12-01 00:06:20 25 4
gpt4 key购买 nike

我正在从我的 React 类组件中的 API 请求数据。在 fetchData 方法中,我将 State 设置为一个名为 data 的键,该键最初只是一个空对象。使用 fetchData 方法,该对象将填充来自 API 的数据结果。我将结果传播到数据对象中,并在对象内添加一个“directors”键,该键是一个由于过滤方法而创建的数组。我的问题是我需要directors 数组的长度,但 this.state.data.directors.length 导致错误说它未定义。但是, this.state.data.directors 成功地将数组返回给我,当我打开数组时,我可以在控制台中看到 length 属性是我实际需要的数字。这是我的代码的一个版本。

constructor(){
super();
this.state={
data: {},
};
}

fetchData = async movieId => {

try{
const endpoint = `${API_URL}movie/${movieId}?api_key=${API_KEY}`;
const result = await(await fetch(endpoint)).json();
const creditsEndpoint = `${API_URL}movie/${movieId}/credits?api_key=${API_KEY}`;
const creditsResult = await (await fetch(creditsEndpoint)).json();
const directors = creditsResult.crew.filter(member => member.job === 'Director');

this.setState({
data: {
...result,
actors: creditsResult.cast,
directors
}
}, () => {
localStorage.setItem(`${movieId}`, JSON.stringify(this.state.data));
});

}catch(error){
this.setState({error: true});
alert(error);
}
this.setState({loading: false});
}

componentDidMount(){
const {movieId} = this.props.match.params;

if(localStorage.getItem(`${movieId}`)){
console.log("grabbing from localStorage" + " " + movieId);
this.setState({
data: JSON.parse(localStorage.getItem(`${movieId}`))
});
} else {
console.log("Grabbing from API");
const {movieId} = this.props.match.params;
this.setState({loading: true});
this.fetchData(movieId);
}
}

render(){
const {data} = this.state;
console.log(this.state.data.directors.length);
return(

我希望从 Controller 数组中获取 length 属性,因为 console.logging Controller 数组返回一个包含对象的数组。

最佳答案

您没有定义directors数组的初始状态。因此,在 API 请求得到解决之前,directors 是未定义的

this.state = {
data: {
directors: []
}
}

关于javascript - React 无法读取未定义的属性 'length' 但数组已定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60357339/

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