简体   繁体   English

是否可以在反应渲染中创建一个 function 包含一个 if 语句到 setState

[英]Is it possible to create a function inside react render that contains an if statement to setState

So my app takes three random values from an array inside defaultProps, and displays these inside divs in the return JSX and sets the values of three properties in state.所以我的应用程序从 defaultProps 中的数组中获取三个随机值,并在返回的 JSX 中显示这些内部 div,并在 state 中设置三个属性的值。

I need to change the state depending on what these random values are (if random1 === random2 || random2 === random3).我需要根据这些随机值是什么来更改 state(如果 random1 === random2 || random2 === random3)。 I have put ternary operators inside console.logs inside the main div and they output exactly what I want.我已将三元运算符放在主 div 内的 console.logs 中,它们 output 正是我想要的。 However, when I attempt to create a function with an if else statement in the same place, it does not change the state.但是,当我尝试在同一位置创建带有 if else 语句的 function 时,它不会更改 state。 I'm imagining this is an issue with scope?我想这是 scope 的问题?

Any help much appreciated.非常感谢任何帮助。

This is the code I have tried to use:这是我尝试使用的代码:

this.state = { 
    fruit1: "🤑", fruit2: "🍒", fruit3: "🍹", 
    rolling: false, win: false, bigWin: false, 
    bankAccount: 0 
  };

... ...

render (
        <div class="main-div">
          {function winCheck() {
        if (this.state.fruit1 === this.state.fruit2) {
          this.setState({ win: true })
        } else {
          this.setState({win: false})
        }
      }}
      </div>
      )

You can't do that inside render.你不能在渲染中做到这一点。 You should make a function that returns true or false depending the state values.您应该制作一个 function,它根据 state 值返回 true 或 false。

const hasWon = () => {
    const { fruit1, fruit2 } = this.state;
    return fruit1 === fruit2;
}

Then in the render:然后在渲染中:

render (
    <div class="main-div">
      {this.hasWon() ? /* WON COMPONENT */ : /* LOOSE COMPONENT */}
    </div>
  )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM