【发布时间】:2018-12-22 18:46:51
【问题描述】:
我正在制作一个简单的 Todo 列表,其中包含一个容器 App 组件以及一个子 Todo 无状态功能组件。当我创建一个新的 todo 时,我希望它被添加到我在父组件状态中定义的 todos 数组中。但是,当我这样做时,我收到错误:Uncaught TypeError: this.state.todos.map is not a function。有人可以帮我理解这是为什么。
这里是父组件:
class App extends Component {
constructor(props){
super(props);
this.state = {
input: '',
todos: [
'buy milk',
'buy eggs',
'take out trash'
]
};
this.handleSubmit=this.handleSubmit.bind(this);
this.handleChange=this.handleChange.bind(this);
}
handleSubmit(e){
let value = this.state.input;
let todos = this.state.todos;
let newTodos = todos.push(value);
this.setState({todos: newTodos, input: ''});
}
handleChange(e){
this.setState({input: e.target.value})
}
render() {
let todolist = this.state.todos.map((value, index) => {
return(
<ul>
<Todo value={value} />
</ul>
)
})
return (
<div>
<h1>My Todo list</h1>
<form onSubmit={this.handleSubmit}>
<input
type='text'
onChange={this.handleChange}
value={this.state.input}
/>
<input type='submit'/>
</form>
{todolist}
</div>
);
}
}
这是子组件:
let Todo = (props) => {
return(
<li>{props.value}</li>
)
};
【问题讨论】:
标签: javascript reactjs react-native react-redux jsx