【发布时间】:2019-02-25 12:27:48
【问题描述】:
我正在构建一个简单的待办事项列表。我有一个用于添加新的待办事项列表项的表格,在它下面列出了待办事项列表中的所有项目。当我通过表单添加新项目时,我想刷新现有待办事项列表项的列表。
Items.jsx:
class Items extends React.Component {
constructor(props) {
super(props);
this.state = {
items: [],
loading: true
};
}
componentDidMount() {
axios.get('/api/v1/items')
.then(response => {
this.setState({ items: response.data, loading: false });
});
console.log('state.items: '+this.state.items);
}
componentDidUpdate() {
axios.get('/api/v1/items')
.then(response => {
this.setState({ items: response.data, loading: false });
});
console.log('componentDidUpdate: '+this.state.items);
}
render() {
return (
<ItemSE.Group>
{
this.state.items.map(item => {
return <Item key={item.id} data={item} />
})
}
</ItemSE.Group>
);
}
}
export default Items
App.jsx:
class App extends Component {
constructor () {
super();
this.state = {
item_msg: ''
}
this.handleInputChange = this.handleInputChange.bind(this);
}
handleSubmit(e){
e.preventDefault();
console.log(this.state.item_msg);
axios.post('/api/v1/items', {
item: this.state.item_msg
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
handleInputChange(e) {
this.setState({ item_msg: e.target.value });
console.log('item_msg: '+this.state.item_msg);
}
render() {
return (
<div className="App">
<MainHeaderr />
<Container>
<NewItemForm
send_form={this.handleSubmit.bind(this)}
onInputChange={this.handleInputChange}
typed={this.state.item_msg} />
<Items />
</Container>
</div>
);
}
}
export default App;
我将componentDidUpdate 添加到Items.jsx 文件中——当我添加一个新的待办事项列表时,这个新的待办事项确实会立即显示到列表中——这很酷。但是,我真的不觉得这是最好的做法。
当我查看 JS 控制台时,我看到有数百个 componentDidUpdate:。
那么,刷新待办事项列表的最佳方式是什么?
【问题讨论】:
-
您不应该在没有条件检查的情况下使用componentDidUpdate,否则会因为componentDidUpdate中的setState导致无限循环或重新渲染和API调用
-
你可以将
items存储在App组件中,然后传入Items组件的props——这种方式有点丑,所以很多人都在使用Redux/Relay来存储全局数据 -
你不能只将新项目添加到列表中而不是获取完整列表吗?
标签: javascript reactjs