简体   繁体   English

React Context API-表单输入未定义

[英]React Context API - form input is undefined

I'm trying to build simple todo application with new context API but I'm having a hard time trying to debug why my input value is undefined. 我正在尝试使用新的上下文API构建简单的待办事项应用程序,但是我很难调试我的输入值未定义的原因。

I don't quite understand how to execute a function provided by Provider and pass arguments to it. 我不太了解如何执行Provider提供的功能并将参数传递给它。

here is my code: 这是我的代码:

import React, { Component } from "react";
import logo from "./logo.svg";
import "./App.css";
const AppContext = React.createContext();

class AppProvider extends Component {
  constructor(props) {
    super(props);
    this.state = {
      todoList: [{ text: "first test element", isCompleted: false }]
    };
  }

  addTodo = (e) => {
    e.preventDefault();
    console.log(e.target.value);
    this.setState({
      todoList: [
        ...this.state.todoList,
        { text: e.target.value, isCompleted: false }
      ]
    });
  };

  render() {
    const { todoList, uniqueId } = this.state;
    return (
      <AppContext.Provider
        value={{ todoList, addTodo: this.addTodo }}
      >
        {this.props.children}
      </AppContext.Provider>
    );
  }
}

const Consumer = AppContext.Consumer;

class App extends Component {
  constructor(props) {
    super(props);
    this.state = { value: "" };
  }
  render() {
    return <AppProvider>
        <div className="App">
          <header className="App-header">
            <img src={logo} className="App-logo" alt="logo" />
            <h1 className="App-title">TodoList</h1>
          </header>
          <Consumer>
            {state => <form onSubmit={state.addTodo}>
                <input type="text" />
                <button type="submit" onSubmit={state.addTodo}>
                  Add Todo
                </button>
              </form>}
          </Consumer>
          <Consumer>
            {val => (
              <ul>
                {val.todoList.map((item, index) => (
                  <li key={index}>{item.text}</li>
                ))}
              </ul>
            )}
          </Consumer>
        </div>
      </AppProvider>;
  }
}

export default App;

Sorry if my questions is trivial but I've been trying to solve it for quite a bit and I can't find what's wrong. 抱歉,如果我的问题很琐碎,但我已经尝试解决很多问题了,所以我找不到问题所在。

You just had some issues with how your form was sending the value through. 您只是在表单如何传递值方面遇到一些问题。 Also, you should try decouple your events and your state, as shown in the working example here . 此外,你应该尝试解耦事件和你的状态中,如在工作实例这里

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

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