【问题标题】:React cannot read property 'length' of undefined but array is definedReact 无法读取未定义的属性“长度”,但数组已定义
【发布时间】:2020-06-06 23:40:37
【问题描述】:

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

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(

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

【问题讨论】:

  • 看起来 director 键是在 componentDidMount 中异步设置的,所以它可能在后续渲染之前实际上不可用。如果this.state.data.directorsundefined,您可能会想以某种方式防范这种情况,可能会呈现某种“正在加载...”指示符
  • 您可以做两件事。使用空数组定义初始状态,或者在填充数据之前阻止渲染(例如返回预加载器组件)

标签: javascript arrays reactjs


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2018-02-10
    • 2020-07-20
    • 2020-03-07
    • 2021-11-29
    • 2021-10-03
    • 1970-01-01
    • 1970-01-01
    • 2011-11-01
    • 1970-01-01
    相关资源
    最近更新 更多