首页 > 解决方案 > 当内容嵌套在数组中时,React 看不到“标记更改”

问题描述

我遇到的问题是 React 在以下情况下没有更新。
当组件应该更新时,我添加了一个 forceUpdate() 以确保更加确定。

代码很简单,所以没什么好说的。
就好像 React 没有看到它应该更新或者我在这里做错了什么?

class Greetings extends React.Component{
  constructor(props){
    super(props)
    this.switchLanguage = this.switchLanguage.bind(this)
    this.state = {
      languageID: 0,
    }
    
    this.arrayContainingRenderValues = [
        <span>{this.props.greetingArray[this.state.languageID]}!</span>,
        <span>No greetings for you!!</span>
      
    ]
  }
  
  switchLanguage(){
    this.setState((previousState) => ({languageID: (previousState.languageID + 1) % this.props.greetingArray.length}))
    
    
    this.forceUpdate()
  }
  
  componentDidMount(){
    this.timerID = setInterval(this.switchLanguage, 500)
  }
  componentWillDismount(){
    clearInterval(this.timerID)
  }
  
  render(){
    return this.arrayContainingRenderValues[0]

    //The return below works without problem
    return <span>{this.props.greetingArray[this.state.languageID]}!</span>
  }
}


let content = <Greetings greetingArray={["Good morning","Bonjour","Buenos días","Guten tag","Bom dia","Buongiorno"]}/>

ReactDOM.render(content, document.getElementById('root'))

啊,这段代码是一个例子,我真的不需要它来工作,但如果它需要它会很好。谢谢。

标签: javascriptreactjsnested

解决方案


问题

当您this.arrayContainingRenderValues在构造函数中定义时,您包含了当前/初始this.state.languageID值,因此this.state.languageID以后的任何更新都不会更新这个陈旧的外壳。this.arrayContainingRenderValues每次状态更新时,您都希望重新计算值。当您移动数组进行渲染时,您每次都在重新计算。

解决方案

this.props.greetingArray如果为空(或未通过),您似乎正在尝试应用一些条件渲染。

class Greetings extends React.Component {
  constructor(props) {
    super(props);
    this.switchLanguage = this.switchLanguage.bind(this);
    this.state = {
      languageID: 0
    };
  }

  switchLanguage() {
    this.setState((previousState) => ({
      languageID:
        (previousState.languageID + 1) % this.props.greetingArray.length
    }));
  }

  componentDidMount() {
    this.timerID = setInterval(this.switchLanguage, 500);
  }
  componentWillDismount() {
    clearInterval(this.timerID);
  }

  render() {
    return this.props.greetingArray.length ? (
      <span>{this.props.greetingArray[this.state.languageID]}!</span>
    ) : (
      <span>No greetings for you!!</span>
    );
  }
}

演示

编辑 react-does-not-see-that-the-markup-changes-when-content-is-nested-in-array


推荐阅读