伙计们!当页面加载或重新加载时,我试图将待办事项列表保存到localStorage并获取它。但是此localStorage清除后。怎么了你知道吗可能是我使用了不合适的组件生命周期方法吗? 组件安装后,我在localStorage todos列表中检查可用性。之后,我将数组保存到localStorage,然后组件将更新。
列表组件:
import React from 'react'
import { connect } from 'react-redux'
import Todo from './Todo'
import AddTodoForm from './AddTodoForm'
import { checkTodos } from '../actions/index';
import './TodoList.css'
class TodoList extends React.Component {
componentDidMount() {
if (localStorage.getItem("todos")) {
this.props.check(JSON.parse(localStorage.getItem("todos")));
}
};
componentWillUpdate(nextProps, nextState) {
localStorage.setItem("todos", JSON.stringify(nextProps.todos));
};
render() {
return (
<div>
<AddTodoForm />
{ this.props.todos && this.props.todos.length !== 0 ?
<table>
<thead>
<tr>
<th>#</th>
<th>Title: </th>
<th>Status: </th>
</tr>
</thead>
<tbody>
{ this.props.todos.map((todo) => <Todo key={todo.id} todo={todo} />) }
</tbody>
</table> : <span>There no todos yet</span> }
</div>
);
};
};
const mapStateToProps = (state) => ({ todos: state.todos });
const mapActionsToProps = (dispatch) => ({ check: (todos) =>
dispatch(checkTodos(todos)) });
export default connect(mapStateToProps, mapActionsToProps)(TodoList);
减速器:
const todoReducer = (state = [], action) => {
switch (action.type) {
case "CHECK_TODOS":
return [...state];
case "ADD_TODO":
return [...state, action.payload];
case "REMOVE_TODO":
return state.filter((todo) => todo.id !== action.payload);
case "TOGGLE_COMPLETED":
return state.map((todo) => todo.id === action.payload ?
{...todo, completed: !todo.completed} : todo);
default:
return state;
}
};
export default todoReducer;