首页 > 解决方案 > React 无法将状态值传递给状态数组

问题描述

在 React 中,我有一个名为 random 的状态属性,带有一个随机值。我正在尝试选择具有随机状态的 myArray2 值并将其传递到 myArray 状态中。

当我单击按钮时,警报方法应该显示其中一个随机数,但它似乎不起作用。

import React, { Component } from 'react';
import './App.css';



class App extends Component {

  //random = Math.floor(Math.random() * 3)

  constructor(props){
    super(props);

this.state = {
    random: Math.floor(Math.random() * 3),
    myArray2:['one','two','three'],
    myArray:this.state.myArray2[this.state.random]     
};

}

change = () => {
  alert(this.state.myArray);
}

  render() {
    return (
      <div className="App">
        <button onClick={this.change}>ok</button>
      </div> 

    );
  }


}

export default App;

这就是我得到的——

TypeError:无法读取未定义的属性“myArray2”

这就是我要的-

显示随机数的警报方法

标签: reactjs

解决方案


这是目前基于类的组件无法做到的。但是,您可以让您的change()函数自己执行随机逻辑并有效地更新 random 和 myArray 状态。

this.setState()有第二个回调参数,它使我们能够访问更新的状态。使用它来触发警报。

this.state = {
    random: Math.floor(Math.random() * 3),
    myArray2:['one','two','three'],
    myArray: null
};


  change = () => {
    const random = Math.floor(Math.random() * 3);
    this.setState(
      {
        random: random,
        myArray: this.state.myArray2[random]
      },
      () => alert(this.state.myArray) //now refers to the new state value
    );
  };

请参阅沙箱以供参考:https ://codesandbox.io/s/confident-meadow-jumty


推荐阅读