我使用 react 在 javascript 中创建了一个待办事项列表,因为我是 react 的初学者,所以我使用“this.state”在多个组件中更改我的应用程序的状态,我的问题是在面试时我被分配了一项任务使用 mobx 创建待办事项列表来运行其状态,但是经过长时间的研究,我仍然有很多转换我的反应项目的“this.state.todo”的问题,这是代码中的主要应用程序组件,我希望演示如何将状态转换为 mobx 观察者/可观察者,如果需要更多组件,我希望添加它们
import React from 'react';
import _ from 'lodash';
import TodoCreate from './todo-create';
import TodoList from './todo-list';
import 'semantic-ui-css/semantic.min.css';
import { Header } from 'semantic-ui-react';
import {decorate, observable} from "mobx"
import {observer} from "mobx-react"
export default class App extends
React.Component {
constructor(props) {
super(props);
this.state = {
todos : todos
}
this.createTask = this.createTask.bind(this);
this.saveTask = this.saveTask.bind(this);
this.deleteTask = this.deleteTask.bind(this);
this.toggleTask = this.toggleTask.bind(this);
}
createTask(task) {
this.state.todos.push({
task,
isCompleted: false,
creationDate:new Date().toLocaleTimeString() + new Date().toLocaleDateString(),
updateDate:new Date().toLocaleTimeString() + new Date().toLocaleDateString()
});
this.setState({ todos: this.state.todos });
}
deleteTask(taskToDelete) {
_.remove(this.state.todos, todo => todo.task === taskToDelete);
this.setState({ todos: this.state.todos });
}
saveTask(oldTask, newTask) {
const foundTodo = _.find(this.state.todos, todo => todo.task === oldTask);
foundTodo.task = newTask;
foundTodo.updateDate = new Date().toLocaleTimeString() + new Date().toLocaleDateString();
this.setState({ todos: this.state.todos });
}
toggleTask(task) {
const foundTodo = _.find(this.state.todos, todo => todo.task === task);
foundTodo.isCompleted = !foundTodo.isCompleted;
foundTodo.updateDate = new Date().toLocaleTimeString() + '' + new Date().toLocaleDateString();
this.setState({ todos: this.state.todos });
}
render() {
return (
<div>
<div className="wrap">
<div className="header">
<Header as="h2" className="headerclass">ls-tech Todo-list</Header></div>
<div className="wrap-list">
<div className="td-list-con">
<TodoCreate
todos={this.state.todos}
createTask={ this.createTask}
/>
<TodoList
todos={ this.state.todos }
saveTask={ this.saveTask }
deleteTask={ this.deleteTask }
toggleTask={ this.toggleTask }
/>
</div>
</div>
</div>
</div>
)
}
}