增加React中每个元素添加的ID

时间:2018-05-25 05:42:02

标签: arrays reactjs loops

我遇到了一个问题,我无法为行中每增加一个元素增加state元素的ID。我得到的是相同的数字是每次添加元素重复,我需要ID之类的东西应该是1到n个加法。 在文本框中,我没有输入ID,我只输入LText(名称)。 通常,ID应该为每次添加元素生成。 我试过的是......

    export default class EPIM091 extends cntrl.WITBase {
    constructor(props) {
        super(props);
        const witState = this.state;
        if (Object.keys(witState).length == 0) {
            witState.model = { LID: 1, LText: '', SOrder: '', Inventoried: false, Location:[] }; //Here i need to store all other state values to the Location Array
}
}
 clickAction = (e) => {
if (e.id == 'btn_add') {
            //var i = 1;
            const { model } = this.state;
            if (model.LText != null) {
                if ((model.Location || []).length == 0) {
                    model.Location = [];
                }
                // this.setState(prevState => { return { LID: e.id == 'btn_add' ? prevState.LID + 1 : prevState.LID - 1 } }); //This does not worked
                model.Location.push({ "LID": model.LID.toString(), "LText": model.LText, "SOrder": model.SOrder, "Inventoried": model.Inventoried.toString() });
                this.setState({
                    model: model,
                    LID: model.LID + 1 //This also not worked
                });
            }
        }
    };
       render(){
// Due to confusion of code, i did not add the textboxes codes
<cntrl.WITButton id="btn_add" onWitClick={this.clickAction} />
}

enter image description here

我需要像我添加的东西一样,我应该从1添加唯一LID到添加的元素数量。我得到的是相同的ID,即1.谢谢

1 个答案:

答案 0 :(得分:0)

这里有很多问题:

1)您正在尝试修改您声明为常量的变量:

const witState = this.state;
        if (Object.keys(witState).length == 0) {
            witState.model = { LID: 1, LText: '', SOrder: '', Inventoried: false, Location:[] };

2)您正在尝试访问状态变量,但您从未定义它:

const { model } = this.state;

3)即使声明为常量,您也会尝试修改它:

if (model.LText != null) {
                if ((model.Location || []).length == 0) {
                    model.Location = [];
                }
                // this.setState(prevState => { return { LID: e.id == 'btn_add' ? prevState.LID + 1 : prevState.LID - 1 } }); //This does not worked
                model.Location.push({ "LID": model.LID.toString(), "LText": model.LText, "SOrder": model.SOrder, "Inventoried": model.Inventoried.toString() });
                this.setState({
                    model: model,
                    LID: model.LID + 1 //This also not worked
                });
            }

除非您没有向我们展示很多代码,否则您的控制台中必定会出现很多错误。看着它。

- [编辑] -

问题在于,除非我拥有整个代码,否则我无法真正帮助你,因为它实际上并没有意义。如果您只想增加LID状态var,这是一个有效的例子:

constructor(props) {
   super(props);
   this.state={LID:1}
}
test=(e)=>{
    let {LID} = this.state;
    this.setState({LID:LID+1})
    console.log(this.state.LID);
 }
 render(){
     return(
         <button onClick={this.test}> Test</button>
     )
 }