首页 > 解决方案 > 参考错误“'状态中的数组名称'未定义”

问题描述

我似乎无法在我的数组中设置属性的状态,因为 react 认为它是未定义的,或者我猜它显然是未定义的,谁能告诉我我的代码有什么问题!

构造函数中的状态

constructor(props){
            super(props);
            this.state = {
                listOfItems: [],
                listOfEquiptment: [],
                listOfSpells: [],
                choosableEquiptment:[],
                choosableSpells: [],
                currentEquiptment: undefined,
                currentSpell: undefined
            }
            this.addNewEquiptment =this.addNewEquiptment.bind(this);
            this.addNewSpell =this.addNewSpell.bind(this);
            this.handleEquiptmentChange = this.handleEquiptmentChange.bind(this);
            this.handleSpellChange = this.handleSpellChange.bind(this);
    }

**我正在尝试重新分配的财产**

if(prevProps.chosenCharacter != this.props.chosenCharacter){
            axios.get(`/api/${this.props.chosenUser.name}/characters/${this.props.chosenCharacter.name}`)
            .then(results =>{
                let newArr = results.data;
                // newArr.sort((a, b) => {
                //     return (a.item > b.item ? 1 : -1)
                // })
                console.log("arr after sort is", newArr)
                this.setState({
                    listOfItems: newArr
                });
                console.log('list of items after set state ', listOfItems)
                .then(results =>{
                    const tempEquipArr = [];
                    const tempSpellArr = [];
                    for(const item of listOfItems){
                        (item.type == "spell")? tempSpellArr.push(item.name) : tempEquipArr.push(item.name);
                    }
                })
                this.setState({
                    listOfEquiptment: tempEquipArr,
                    listOfSpells:tempSpellArr
                })
            })
            .catch(err =>{
                console.error(err);
            })  
        }

标签: javascriptreactjsstate

解决方案



推荐阅读