亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

React Hooks,useState 相關問題。如何更新對象的一個??屬性并保留其余的

React Hooks,useState 相關問題。如何更新對象的一個??屬性并保留其余的

慕森王 2023-04-27 16:56:26
我想用掛鉤做一個待辦事項列表。這是我的相關代碼。function generateId() {  return '_' + Math.random().toString(36).substr(2, 9);};export function TodoList(){  const [todos, setTodos] = React.useState([])  const [input, setInput] = React.useState('')  const [time, setTime] = React.useState('')  const handleSubmit = () => {    setTodos((todos) => todos.concat({      text: input,      id: generateId(),      timeRequired: time,    }))    setInput('')    setTime('')  }  // remove to do works fine.  const removeTodo = (id) => setTodos((todos) => todos.filter((todo) => todo.id !== id ))  /// confusion here   let todo = (id) => todos.find(x => x.id = id)  const decrement = (id) => setTodos((todo(id).timeRequired) => timeRequired - 1)   ///   return(    <React.Fragment>      <input type="text" value={input} placeholder="New Task" onChange={(e) => setInput(e.target.value)}>       </input>      <input type="number" value={time} placeholder="Hours Required" onChange={(e) => setTime(e.target.value)}>      </input>      <button onClick={handleSubmit}> Submit </button>      <ul>        {todos.map(({text, id, timeRequired}) => (          <li key={id}>            <span>{text}: remaining {timeRequired} hours </span>             <button onClick={() => removeTodo(id)}>               Cancel ?             </button>            <button onClick={() => decrement(id)}> Decrement ? </button>             <button > Increase ? </button>             <button> Done ?? </button>          </li>        ))}      </ul>    </React.Fragment>  )}所以我想增加/減少待辦事項列表上的剩余時間。但是,我不知道如何選擇列表中的特定項目并更改一個屬性(剩余時間)并保留文本屬性。
查看完整描述

4 回答

?
翻閱古今

TA貢獻1780條經驗 獲得超5個贊

下面是該decrement函數的外觀。這需要id, 循環遍歷所有todos. 如果 atodo與提供的不匹配,id請保持原樣。如果確實匹配,則創建對象的淺表副本 ( ) 并使用更新后的值{...todo}覆蓋該屬性。timeRequired


const decrement = (id) => setTodos((todos) => todos.map((todo) => {

  if (todo.id != id) return todo;

  return {...todo, timeRequired: todo.timeRequired - 1};

}));

請注意,順序{...todo, timeRequired: todo.timeRequired - 1}很重要。通過放置在它將覆蓋現有屬性timeRequired: todo.timeRequired - 1之后。...todo就像 object{a: 1, b: 2, a: 3}會把 object 留給你一樣{a: 3, b: 2},因為 key 的第二個定義a覆蓋了第一個。


查看完整回答
反對 回復 2023-04-27
?
至尊寶的傳說

TA貢獻1789條經驗 獲得超10個贊

你可以這樣試試



  const decrement = (id) => {

    

    const targetTodo = todos.find(x => x.id == id);  //get the todo


    const currentTime = targetTodo.timeRequired -1 //decrease the time 

    

    const newTodo = { ...targetTodo , timeRequired : currentTime } // create new todo object

    

    const newTodoList = todos.map( item => { // finally replace the old todo object

        if(item.id = id)  return newTodo

        else return item;

    })

    

    setTodos(newTodoList) 


  }


查看完整回答
反對 回復 2023-04-27
?
慕尼黑5688855

TA貢獻1848條經驗 獲得超2個贊

識別數組中的元素后,從 todo 創建一個具有遞減timeRequired屬性的新對象。然后使用.slice在新項前后對數組進行切片,新項在中間:


const decrement = (i) => {

    const replacedTodo = {

        ...todos[i],

        timeRequired: todos[i].timeRequired - 1,

    };

    setTodos(

        todos.slice(0, i),

        replacedTodo,

        todos.slice(i + 1),

    );

};

{todos.map(({ text, id, timeRequired }, i) => (

  // ...

  <button onClick={() => decrement(i)}> Decrement ? </button>

.map直接使用函數中的索引比稍后從 ID 中查找匹配元素更容易。


查看完整回答
反對 回復 2023-04-27
?
一只甜甜圈

TA貢獻1836條經驗 獲得超5個贊

嘗試這個...


const removeTodo = (id) => setTodos((todos) => todos.filter((todo) => todo.id !== id ))

const decrement = (id) => setTodos((todos) => todos.map((todo) => {

  const {

    id: oldID,

    timeRequired,

  } = todo;

  return {

    ...todo,

    timeRequired: id===oldID? timeRequired-1 : timeRequired, 

  };

}));


查看完整回答
反對 回復 2023-04-27
  • 4 回答
  • 0 關注
  • 290 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號