reactjs - 使用 React Js 创建一个简单的 todolist。不知道为什么我的状态没有用新的 todo 项更新
问题描述
我基本上是在制作一个 todolist 应用程序。我只希望用户输入文本并将其添加到我的状态中。但是当我单击按钮时,状态没有使用新的 todoItem 更新。请帮助解决这个问题。
我的状态在Context.js
import React from 'react';
const Context=React.createContext();
const reducer=(state,action)=>{
switch(action.type){
case "ADD_TODO":
return {
...state,
todos:[action.payload,...state.todos]
}
default:
return state;
}
}
export class Provider extends React.Component{
state={
todos:[
{id:"1",todoItem:"Code daily"},
{id:"2",todoItem:"play"},
{id: '16a1c935-a033-4272-85b4-4412de42b59f', todoItem: 'wdwdwd'},
],
dispatch:action=>{
this.setState(state=>{
reducer(state,action)
})
}
}
render(){
return(
<Context.Provider value={this.state}>
{this.props.children}
</Context.Provider>
)
}
}
export const Consumer=Context.Consumer;
我的输入组件,用于从用户那里获取 todoitem 输入并将其添加到状态中。但是我的页面正在重新加载,但我的用户输入的文本没有添加到状态中。并且没有显示错误。
InputTodo.js
import React, { Component } from 'react';
import '../css/InputTodo.css';
import { v4 as uuidv4 } from 'uuid';
import {Consumer} from '../context';
class InputTodo extends Component {
constructor(props){
super(props);
this.state={
inputValue:""
};
}
OnChange(event){
const txtEntered=event.target.value;
this.setState({
inputValue:txtEntered,
});
}
handleButtonClicked=(dispatch,event)=> {
event.preventDefault();
const inputValue=this.state.inputValue;
const newTodo={
id:uuidv4(),
todoItem:inputValue,
}
dispatch({type:'ADD_TODO',payload:newTodo});
this.setState({
inputValue:"",
});
this.props.history.push('/');
}
render() {
return(
<Consumer>
{value=>{
const {dispatch}=value;
return (
<form onSubmit={this.handleButtonClicked.bind(this,dispatch)}>
<div className="form-group">
<input value={this.state.inputValue} onChange={this.OnChange.bind(this)} className="form-control" placeholder="Enter the todo" />
<button type="submit" className="btn btn-primary">Add</button>
</div>
</form>
)}}
</Consumer>
)
}
}
export default InputTodo;
解决方案
您只是忘记了return
dispatch 中的新状态setState
:
export class Provider extends React.Component{
state={
/* ... */
dispatch:action=>{
this.setState(state=>{
return reducer(state,action) /* <--- Here you missed the return */
})
}
}
/* ... */
推荐阅读
- visual-studio - Visual Studio for Mac:无法添加 Web 参考
- javascript - 如何使标签内容在 javascript 中处于活动状态?
- bash - 使用 sed 删除多个 AWS 错误
- c++ - c++测试程序中的非法系统调用(对角矩阵元素之和程序)
- jsf-2 - 已使用 @Transactional 注释的方法中的 TransactionRequiredException
- node.js - 事后如何编写 HTTP 500 错误标头
- mql4 - MQL4 只需添加到一张图表即可在所有交易品种上运行 EA
- nginx - SignalR .NET Core 2.1 不适用于代理的 docker 容器
- sql-server - 可以提取存储在 XML 中的列中的 *distinct* 键(跨所有行)吗?
- python - PyQt GUI 项目在其主类之外