简体   繁体   中英

How do I get the UI to render with my state with react

I have an onClick method to react that changes the state of a property named pointer. The function works on a functional level however the UI does not update with my state unless I double click the button (onClick method). I tried turning the component to a class component to utilize the render method but still no results.

let questions = [
  {
    id: 1,
    title: "This person tends to be quiet"
  },
  {
    id: 2,
    title: "This person is compassionate and has a soft heart."
  },
  {
    id: 3,
    title: "This person is disorganized.."
  }
]
export default class Quiz extends React.Component {
  constructor() {
    super();
    this.state = {
      pointer: 0,
      currentAnswer: ""
    };
  }
  render() {
    return (
<div>
<h1> {questions[this.state.pointer].title}</h1>
<button onClick={(e) => {
                    e.preventDefault();
                      this.setState({
                        pointer: this.pointer++
                      });
                      console.log(this.pointer);
                      this.forceUpdate();
                    }}>
</div>
)
}

The issue was I needed to put "this.state.pointer + 1" not " this.pointer++ ".Thanks, icepickle

You just write it, but at least I will give you an explanation.

Every action on State must be performed in a inmutable manner, basically that means that when you call a setState function, the operation provided to setState must return a new value instead of altering the state directly.

Please take this into account for later operations as it will introduce horrendous side effects on your application.

you can read about it here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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