简体   繁体   English

无法将项目推入 React Js 中的列表

[英]Not able to push item into List in React Js

I want to push the tip which I'm calculating in #this.calculate onto tip_arr[].我想将我在#this.calculate 中计算的小费推到tip_arr[] 上。 In that I'm not able to access my first item of as it is showing ["",item,item].因为我无法访问我的第一项,因为它显示 ["",item,item]。 Here my first item is getting empty just the string.在这里,我的第一项只是字符串变空。 Here I'm calculating per person tip how much he is paying and after that diplay that.在这里,我正在计算每人小费他支付了多少,然后显示。

export default class Calculation extends React.Component {导出默认 class 计算扩展 React.Component {

constructor(props) {
    super(props)
    this.state = {
        amount: '',
        tip_per: '',
        name: '',
        tip: '',
        name_arr:[],
        tip_arr:[]
    }

    this.handle = (event) => {
        this.setState({ tip_per: event.target.value });
    }

    this.calculate = () => {
        this.setState({ tip: ((this.state.amount) * this.state.tip_per) / 100 })
        this.name_change()
        this.tip_change()
    }

    this.name_change=()=>{
        let{name_arr,name}=this.state
        name_arr.push(name)
    }

    this.tip_change=()=>{
       let{tip_arr,tip}=this.state
       tip_arr.push(tip)
    }

}
   render(){
       return(
        <>
        <div className='Header'>
            <header>Tip Calculator<br />Build in React</header>
        </div>

        <div className='Input'>
            <h4>Enter the Bill Amount:-</h4>
            <input type='number' className='width' value={this.state.amount} 
                onChange={(e) => this.setState({ amount: e.target.value })}></input>
            <hr />
            <div className='inner'>
                <p>How was the Service:- <span>
                    <select  onChange={this.handle}>
                        <option>Choose...</option>
                        <option value={20}>Excellent:- 20%</option>
                        <option value={10}>Moderate:- 10%</option>
                        <option value={5}>Bad:- 5%</option>
                    </select>

                    <input type='text' className='filed' placeholder="Customer Name"
                        value={this.state.name} onChange={(e) => this.setState({ name: e.target.value })} />

                    <button type='button' className='filed else' onClick={this.calculate}>Add Customer</button>
                </span></p>
            </div>

        </div>

        <div className='Output'>
            <p>Customer List:-</p><hr />
            <ul className='UL'>
                
               {this.state.name_arr.map((item,index)=>{
                   return <li key={index}>{item} offering a tip of</li>})}
           
           <span>                 <ul className='UL'>
                 {this.state.tip_arr.map((item,index)=>{ 
                     return <li key={index}>{item} rupees </li>})}
              </ul>
              </span>

              </ul>
            {console.log(this.state.name_arr)}
            {console.log(this.state.tip_arr)}
        </div>

</> </>

       )
   }



};

You're attempting to mutate a state variable.您正在尝试改变 state 变量。 You have to update the value via setState .您必须通过setState更新值。 You should also pass setState a function instead of a plain object in this case so that you can access the correct value since state updates are asynchronous.在这种情况下,您还应该setState传递给 function 而不是普通的 object ,以便您可以访问正确的值,因为 state 更新是异步的。

tip_change = () => {
  this.setState((prevState) => {
    const { tip, tip_arr } = prevState;
    return {
      tip_arr: [...tip_arr, tip]
    };
  });
}

You can't change state directly.您不能直接更改state

Do Not Modify State Directly.请勿直接修改 State。

Read how to use state correctly from React documentation从 React 文档中阅读如何正确使用 state

To update it, you need to call this.setState eg:要更新它,您需要调用this.setState例如:

    this.tip_change=()=>{
       let{tip_arr,tip}=this.state
       this.setState(prevState => {
           let newTipArray = [prevState.tip_arr, tip]
           return {tip_arr: newTipArray }
       })
    }

This should also be the case for name_arr state. name_arr state 也应该是这种情况。 eg:例如:

    this.name_change=()=>{
        let{name_arr,name}=this.state 
        
        //name_arr.push(name)      // can't manipulate state directly.
        this.setState(prevState => {
            let newNameArr = [prevState.name_arr, name]
            return {name_arr: newTipArray }
       })
    }

Update: as @Phishy, using second form of setState() that accepts a function rather than an object helps fix some of state quirks because of the asyncronous nature of React state. Update: as @Phishy, using second form of setState() that accepts a function rather than an object helps fix some of state quirks because of the asyncronous nature of React state.

Here is a nice article that explains why to Beware: React setState is asynchronous!这是一篇很好的文章,解释了为什么要小心:React setState 是异步的!

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

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