2021年3月10日星期三

React.js not incrementing after function call in onclick

I need to build a table in order to organize some data. I'm using the "onclick" function in order to call a separate function, which is supposed to increment a state variable up by one. My Chrome Devtools isn't giving me any errors but also isn't updating the stock variable. I'm not sure how to get the state to update and display. Here's my source code:

class App extends React.Component {      constructor(props) {          super(props);            this.state = {              cars: [                  {                      manufacturer: "Toyota",                      model: "Rav4",                      year: 2008,                      stock: 3,                      price: 8500                  },                        {                      manufacturer: "Toyota",                      model: "Camry",                      year: 2009,                      stock: 2,                      price: 6500                  },                        {                      manufacturer: "Toyota",                      model: "Tacoma",                      year: 2016,                      stock: 1,                      price: 22000                  },                        {                      manufacturer: "BMW",                      model: "i3",                      year: 2012,                      stock: 5,                      price: 12000                  },                    ]          };          this.renderCar = this.renderRow.bind(this);          this.handleClick = this.handleClick.bind(this);      }        handleClick() {          this.setState(() => {              return {stock: this.stock + 1}          })      }        renderRow(car, index) {          return (              <tr key={index}>                  <td key={car.manufacturer}>{car.manufacturer}</td>                  <td key={car.model}>{car.model}</td>                  <td key={car.year}>{car.year}</td>                  <td key={car.stock}>{car.stock}</td>                  <td key={car.price}>${car.price}.00</td>                  <td key={index}><input type="button" onClick={car.handleClick} value="Increment" /></td>              </tr>          )      }        render() {          return (              <div>              <table>                  <thead>                  <tr>                      <th>Manufacturer</th>                      <th>Model</th>                      <th>Year</th>                      <th>Stock</th>                      <th>Price</th>                      <th>Option</th>                  </tr>                  </thead>                  <tbody>                      {this.state.cars.map(this.renderRow)}                  </tbody>              </table>              </div>          );      };  }    ReactDOM.render(<App />, document.getElementById("app"))  
https://stackoverflow.com/questions/66575446/react-js-not-incrementing-after-function-call-in-onclick March 11, 2021 at 09:59AM

没有评论:

发表评论