如何更新数组中索引处的字段


  function updateFAQ(e, id) {

    let newFAQList = [...faqDesc];

    console.log(e.target.value);


    newFAQList[id].question = e.target.value;

    //newFAQList[id].answer = e.target.value;

    setfaq(newFAQList);

  }

function EditFAQ(props) {

  return (

    <form>

      <TextField

        name="question"

        onChange={e => props.onChange(e, props.id)}

        value={props.question}

      ></TextField>

      <Divider />

      <TextField

       name="answer"

        value={props.answer}

        onChange={e => props.onChange(e, props.id)}

      ></TextField>

      <button> Save Edit </button>

    </form>

  );

}


  {

        "id": 4,

        "question": "question",

        "answer": "answer"

    },

进入


  {

        "id": 4,

        "question": "changed question",

        "answer": "answer changed"

    },

如何在给定索引处更新问答的常见问题解答?我计划有一个表格来更新给定索引处的常见问题解答列表。我想更新类似示例的内容,但我尝试使用 e.target.name 来获取该字段并将其放在 newFAQList[id].e.target.name= e.target.value 旁边但不起作用


qq_花开花谢_0
浏览 105回答 2
2回答

qq_笑_17

&nbsp;function updateFAQ(e, id) {&nbsp; &nbsp; setfaqDesc(&nbsp; &nbsp; &nbsp; faqDesc.map(faq =>&nbsp; &nbsp; &nbsp; &nbsp; faq.id === id ? { ...faq, [e.target.name]: e.target.value } : faq&nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; );&nbsp; }这会将目标名称设置为目标值 onChange

四季花海

我假设你有一些arrayLst数据,你可以做这样的事情:function updateFAQ( value, desc ) {&nbsp; for (var i in arrayLst) {&nbsp; &nbsp;if (arrayLst[i].value == value) { // i -> index&nbsp; &nbsp; &nbsp;arrayLst[i].desc = desc; // add whatever you want to do.&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; }&nbsp;}}或者//let your array belet arrayLst = [&nbsp; {id: 0, name: "Roy"},&nbsp; {id: 1, name: "John"},&nbsp; {id: 2, name: "Doe"},&nbsp; {id: 3, name: "Angela"}],&nbsp; &nbsp;&nbsp;//Find index of specific object using findIndex method.&nbsp; &nbsp;&nbsp;index= arrayLst.findIndex((obj => obj.id == 1));console.log("Before update: ", arrayLst[index])arrayLst[index].name = "Paul" //John to Paulconsole.log("After update: ", arrayLst[index])
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript