简体   繁体   English

需要帮助弄清楚 React 中的状态

[英]Need Help Figuring Out State in React

I'm working on a basic Todo app.我正在开发一个基本的 Todo 应用程序。 I'm storing the todo items in state as an array of objects.我将状态中的待办事项项存储为对象数组。 The object key is the todo item, the value is either true(done) or false(not done).对象键是待办事项,值为 true(完成)或 false(未完成)。 When I click a button to check off an item, I want to change the value of the todo item as well as change the style of the element to indicate it is done.当我单击一个按钮来勾选一个项目时,我想更改待办事项的值以及更改元素的样式以指示它已完成。

this.state = {items: [...{"todo item": false}]}

handleClick(e, item, index){
        e.preventDefault()
        let newState = [...this.state.items];
        if(this.state.items[index][Object.keys(item)] == false){
            //blue = done
            e.target.parentNode.style.color = 'blue';
            newState[index][Object.keys(item)] = true;
        }
        this.setState({items:newState})
        console.log(this.state.items[index])
}

This is not working.这是行不通的。 I'm assuming that it is because setState is asynchronous.我假设这是因为 setState 是异步的。 I thought to try it this way because I want to send my state object to my database so I can keep track of the "doneness" of each item.我想以这种方式尝试它,因为我想将我的状态对象发送到我的数据库,以便我可以跟踪每个项目的“完成度”。 I don't want to remove the item from my items array.我不想从我的 items 数组中删除该项目。 Any help would be very much appreciated.任何帮助将不胜感激。 Let me know if more information is needed!如果需要更多信息,请告诉我!

I don't think setState is the issue here?我不认为 setState 是这里的问题? The issue is how you modify the color.问题是你如何修改颜色。

For the color, I would use a ternary based off the state variable rather than DOM manipulation.对于颜色,我将使用基于状态变量而不是 DOM 操作的三元。 Something like this answer: ternary operator in jsx to include html with react像这样的答案: jsx 中的三元运算符以包含带有反应的 html

If the state isn't uploading (log it at the start of the function so you can see what it is after the run rather than immediately after), then that's a separate issue.如果状态没有上传(在函数开始时记录它,以便您可以在运行后而不是立即看到它是什么),那么这是一个单独的问题。

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

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