【问题标题】:React mapped function running "setState" isn't updating component运行“setState”的反应映射函数没有更新组件
【发布时间】:2018-11-23 06:23:42
【问题描述】:

我有一个应用程序组件,它采用一个嵌套组件。嵌套组件返回由其局部状态变量之一的长度确定的按钮数量。每个按钮都运行一个程序化的 this.setState() 函数以在单击时显示一组新数据。这是描述的代码,下面是我的问题:

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>

我想更新&lt;Buttons /&gt; 状态,每次单击其中一个按钮时将计数加一。这应该运行 setState() 来更新组件并运行 componentDidUpdate() 函数。问题是,upOne() 函数运行了,但它没有更新组件,因此没有运行 componentDidUpdate() 函数,我不知道为什么。

如果我摆脱 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>
        )
    }
}

它按我的预期工作。

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

【问题讨论】:

  • 我已将您的代码放入 sn-p 中,当它运行时,单击按钮显然会尝试重新渲染,但它当然会失败,因为 count 现在是 1variableState 里面只有一个条目...

标签: javascript reactjs


【解决方案1】:

variableState[count].answers...

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

我不知道您在代码中显示的 variableStates 值是否与您最终使用的相同,但如果您将其更改为 variableState[0].answers...,它可以工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-31
    • 1970-01-01
    • 2019-06-07
    • 1970-01-01
    • 2020-06-08
    • 2023-03-07
    • 2021-04-19
    • 2017-04-20
    相关资源
    最近更新 更多