【问题标题】:setState One State of an Object in a Mapping FunctionsetState 映射函数中对象的一种状态
【发布时间】:2019-03-22 00:34:16
【问题描述】:

我已经处理这个问题两天了。无法在线找到解决方案,此时我认为我做错了。

所以这个应用程序的重点是单击按钮并放下一个苹果。单击该按钮会更改组件中树的状态和类名,从而导致其抖动。 Sass 动画完成了剩下的工作。但我不能改变一个苹果的类名。因此,不能为一个苹果制作动画。我认为它只是改变了所有这些,它们有点重叠。这不是我想要的。

不知道我是否处理错误,但这里是 app.js 的代码:

class App extends Component {

  constructor(props){
    super(props);
    this.state = {
      apples: [],
      treeState: ''
    }
  }

  componentWillMount(){
    this.setState(
      {
        apples: [
      {
        id: '1',
        status: 'present'
      },
      {
        id: '2',
        status: 'present'
      },
      {
        id: '3',
        status: 'present'
      }
    ],
  treeState: 'stagnant'});
  }

  render() {
    return (
      <div className="App">        
        <div className="App-header">
        <img onClick={this.shakeTree.bind(this)} className="grab" alt="grab"/>
          <Apples apples={this.state.apples}/>
          <Tree treeState ={this.state.treeState}/>              
        </div>
      </div>
    );
  }

  shakeTree() {
    var css = (this.state.treeState === "stagnant") ? "shaking" : "stagnant";
    this.setState({"treeState":css}); 
    this.dropApples();
}

  dropApples(){
      let apple;
      var random = 2;
      if(this.state.apples){
        apple = this.state.apples.map(applemon => {   
          if(applemon.id==random){
            this.setState(
              {
                apples: [
              {
                id: random, 
                status: 'falling'
              }
            ]});
          }              
        });  
    }
  }  
}

export default App;

我想要的是在不影响其他苹果的情况下将其中一个苹果的状态更改为“正在掉落”。例如,获取 id 为 2 的苹果并将其状态更改为 'falling'。

您能否告诉我如何完成或指出一些确切的资源来说明它是如何完成的。

【问题讨论】:

    标签: javascript reactjs react-native components react-component


    【解决方案1】:

    您没有正确更新状态。您应该将整个更新的对象返回给 setState

    dropApples(){
          let apple;
          var random = 2;
          if(this.state.apples){
            this.setState(prevState => ({
                apples: prevState.apples.map(apple => {
                    if (apple.id == random) return {...apple, status: 'falling'}
                    return apple
                })
            })) 
        }
    } 
    

    【讨论】:

    • 我现在感觉很好。太感谢了!它就像一个魅力。
    【解决方案2】:

    在 dropApples 上,执行此操作以将状态设置为随机苹果掉落

    this.setState({
        apples: this.state.apples.map(
            apple => apple.id === random ? { ...apple, status: 'falling' } : apple
    })
    

    顺便说一句:setState 是异步的,所以当你多次调用 setState 时,它​​可能没有提交上一次调用,从而导致不一致。

    【讨论】:

    • 啊,没用。不过,那个旁注非常有帮助。谢谢! Shubham 的答案是正确的解决方案。
    猜你喜欢
    • 2020-06-08
    • 2021-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多