我正在尝试做一个简单的任务,使用一个输入框,在其中输入文本并在提交时列出下面的内容。我不知道如何在不刷新的情况下反射(reflect)更改。
App.js
constructor(props){
super(props);
this.state={
todoList:[]
}
}
componentWillMount(){
console.log("mounting app");
axios.get('http://localhost:8888/todoitems').then((res)=>{
this.setState({todoList: res.data});
});
}
save=()=>{
var data={
name:this.refs.newvalue.value,
status:'started'
};
axios.post('http://localhost:8888/todoitem',data).then((res)=>{
console.log("data inserted is":data);
});
}
render() {
return (
<div className="App">
<input type="text" ref="newvalue"/>
<button onClick={this.save}>Submit</button>
<table>
<tbody>
{
this.state.todoList.map(todo => (
<TodoList
key={todo.id}
id={todo.id}
name={todo.name}
status={todo.status}
click={this.update.bind(this,todo.id)}
/>
)})
}
</tbody>
</table>
}
待办列表.js
render() {
return (
<tr onClick={this.props.click}>
<td>{this.props.id}</td>
<td>{this.props.name}</td>
<td>{this.props.status}</td>
</tr>
);
}
这样,更改只会反射(reflect)在刷新中。但我需要即时反射(reflect)变化。我尝试使用 shouldcomponentupdate 和 componentwillupdate,但我看到 nextProps 未定义。我天真地不知道如何继续。请帮个忙。
最佳答案
如果您在保存数据后返回数据,那么您可以通过将返回的数据添加到这样的状态来简单地反射(reflect)更改而不刷新
save=()=>{
var data={
name:this.refs.newvalue.value,
status:'started'
}
axios.post('http://localhost:8888/todoitem',data).then((res)=>{
console.log("data inserted is":data);
// When data is returned after successfull save
// add that data to the "todoList" state.
let todoList = [...this.state.todoList]
todoList.push(data)
// setting back the state will trigger a rerender and will show the changes on screen
this.setState({todoList})
})
}
关于javascript - 在 React 中反射(reflect)更改而不刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47981900/