我正在尝试使用新的上下文API构建简单的todo应用程序但是我很难尝试调试为什么我的输入值未定义。
我不太了解如何执行Provider提供的函数并将参数传递给它。
这是我的代码:
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;
很抱歉,如果我的问题很简单,但我一直试图解决它,我找不到什么问题。