刷新错误“状态数组名称未定义”

时间:2019-12-04 01:50:44

标签: javascript reactjs state

我似乎无法在数组中设置属性的状态,因为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);
            })  
        }

1 个答案:

答案 0 :(得分:0)

您的代码问题的症结在于setState函数。您不应该使用.then()作为this.setState()的后续措施,因为这不是一个承诺。相反,您可以使用built in callback function

通过这种方式,您的setState将如下所示:

this.setState({listOfItems: newArr}, () => {
   console.log('list of items after set state ', listOfItems)
   ///Do whatever you need to after the state change
})