首页 文章

运行“setState”的React映射函数不更新组件

提问于
浏览
0

我有一个app组件,它采用一个嵌套组件 . 嵌套组件返回由其本地状态变量的长度之一确定的多个按钮 . 每个按钮都运行一个程序化的this.setState()函数来显示onClick的一组新数据 . 这是所描述的代码,我的问题如下:

class App extends React.Component {
  render() {
    return (
      <div className='container'>
        <Buttons />
      </div>
    )
  }
}

class Buttons extends React.Component {
  state = {
    variableState,
    count: 0,
    chosen: 0,
  }
  upOne = x => {
    this.setState(prevState => ({
      count: prevState.count + 1,
      chosen: x,
    }))
    console.log('running')
  }
  componentDidUpdate() {
    console.log('componentupdated')
  }
  render() {
    const {variableState, count, chosen} = this.state
    const {upOne} = this
    return (
      <div>
      {
        variableState[count].answers.map((s, t) => <button onClick={() => upOne(t + 1)}>{s}</button>)
      }
      </div>
    )
  }
}

const variableState = [
  {
    answers: [
      'one',
      'two',
      'three',
      'four',
    ]
  }
]

ReactDOM.render(<App />, document.getElementById('app'))
<div id="app"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

我想通过在每次单击其中一个按钮时将计数递增1来更新 <Buttons /> 状态 . 这应该运行setState(),它应该更新组件并运行componentDidUpdate()函数 . 问题是,upOne()函数运行,但它不知道为什么 .

如果我摆脱了Array.map()逻辑并使其成为这样的静态函数:

class Buttons extends React.Component {
    state = {
        variableState,
        count: 0,
        chosen: 0,
    }
    upOne = x => {
        this.setState(prevState => ({
            count: prevState.count + 1,
            chosen: x,
        }))
        console.log('running')
    }
    componentDidUpdate() {
        console.log('componentupdated')
    }
    render() {
        const {variableState, count, chosen} = this.state
        const {upOne} = this
        return (
            <button onClick={() => upOne(1)}>click</button>
        )
    }
}

它按照我的预期工作 .

这是预期的行为还是我错过了什么?

1 回答

  • 1

    variableState[count].answers ...

    一旦计数变为 1variableState[1]undefinedundefined.answers 不存在,您将在控制台中看到抛出的错误 .

    我不知道你're showing in your code is the same as you'在你的结尾使用了 variableStates 值,但是如果你将它改为 variableState[0].answers ......,它就可以了 .

相关问题