对于新手来说,这是最具挑战性的部分之一
ReactJS。您不应该在每个级别上创建有状态组件。
选择州的共同所有者。在您的情况下
Items,没有上级
App组件的数据,组件本身无法更改其状态,因此没有理由将状态保持在该位置。
基本上,您应该将
items数组和
isLoading标志保留在
App组件中,然后将其
Items作为道具简单地传递给。
然后,您可以通过在后端添加新项后重新获取数据来更新列表,也可以将其添加到列表中。
另外,您应该
App在每次输入更改时更新父级的状态。
有两种方法:
您可以使其保持
NewItemForm
状态,然后将onSubmit作为函数prop传递到父事件处理程序中。只是使其不可控制,根本不要保持它的状态,父级将继承此参数
event.target.value
。(现在)。
在两种情况下,它都不会每次都重新呈现您的列表。因此,您应该省略
handleInputChangefrom
App组件。
例如: App.js
constructor(props) { super(props); // Initial state this.state = { items: [], isLoading: false, }}handleSubmit(e){ e.preventDefault(); const { value } = e.target; this.setState({ isLoading: true }); axios.post('/api/v1/items', { item: value }) .then(response => { // there are several ways - choose ONE of them // 1. If server returns you the created item // you can just add this item into the list this.setState(prevState => { return { items: [...prevState.items, response.data], isLoading: false, } }); // 2. But if there are any users who can make changing simultaneously with you // (if not - just imagine it :) ) - it's better to make re-fetch data from server axios.get('/api/v1/items') .then(response => { this.setState(prevState => ({ items: response.data, isLoading: false }); }) .catch(err => { console.log('Something bad is happened:', err) });}最后,只需将数据传递到您的
Items组件中即可。
render() { const { items, isLoading } = this.state; return ( ... <Items items={items} isLoading={isLoading} /> ... )}如果您尚未阅读本文,建议您阅读这篇文章-https: //reactjs.org/docs/thinking-in-
react.html。
希望能帮助到你。



