如何使用react挂钩仅更新所选组件

时间:2019-07-09 11:38:20

标签: react-hooks

我正在使用React钩子编写待办事项列表。 每个添加的项目都有两个下拉列表,用户可以在其中确定任务的紧急程度(紧急值)以及要做的事情需要多长时间(速度值)。 更新任一列表都会将其值添加到“得分”属性中。

通过单击“排序”按钮,我可以根据得分对条目进行排序。

现在的问题是,如果我有一个以上的待办事项具有不同的紧急度和速度值,则两个组件的得分将始终相同。

有人可以帮忙吗?谢谢

def countingValleys(n, s):
    list = []
    for i in range(len(s)):
        d = 0
        if s[i] == "D":
            d = 1
        elif s[i] == "U":
            d = -1
        if len(list) == 0:
            list.append(d)
        else:
            list.append(list[-1] + d)
    num = 0
    for i in range(len(s)):
        if s[i] == "U" and list[i] == 0:
            num += 1
    return num

1 个答案:

答案 0 :(得分:0)

您应该实现一个不同的数据模型来实现。您应该为todos保留一个对象数组(每个todo将是一个对象),并且每个对象都应具有urgency属性,以便可以单独设置。

类似这样的东西:

function App() {

  const [todos,setTodos] = React.useState([
    { id: 'todo1', text: 'This is todo1', urgency: 0 },
    { id: 'todo2', text: 'This is todo2', urgency: 1 }
  ]);
  
  function handleClick(id) {
    setTodos((prevState) => {
      let aux = Array.from(prevState);
      aux = aux.map((todo) => {
        if (todo.id === id) {
          todo.urgency === 0 ? todo.urgency = 1 : todo.urgency = 0;
        }
        return todo;
      });
      return aux;
    });
  }
  
  const todoItems = todos.map((todo) => 
    <li 
      key={todo.id}
      className={todo.urgency === 1 ? 'urgent' : 'normal'}
      onClick={()=>handleClick(todo.id)}
    >
      {todo.text}
      {!!todo.urgency && '<--- This is urgent'}
    </li>
  );

  return(
    <React.Fragment>
      <div>
        Click on the todos!
      </div>
      <ul>
        {todoItems}
      </ul>
    </React.Fragment>
  );
}

ReactDOM.render(<App/>, document.getElementById('root'));
li {
  cursor: pointer;
}

.urgent {
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>

<div id="root"/>

相关问题