javascript - 在 React 中反射(reflect)更改而不刷新

标签 javascript reactjs

我正在尝试做一个简单的任务,使用一个输入框,在其中输入文本并在提交时列出下面的内容。我不知道如何在不刷新的情况下反射(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/

相关文章:

javascript - 如何允许弹出窗口继续弹出,即使您移至另一个页面并且仅在单击按钮时停止?

php - 如何阅读网页的标题部分?

javascript - 如何创建一个以 Node 服务器作为后端的react-redux应用程序?

reactjs - react 和 Redux : Managing Redux Custom Middleware List

javascript - React动态表TH标题不显示

javascript - 如何只打印 `this` 对象的名称,而不是它在 javascript 中的内容?

没有任何 php 代码的 Javascript 文件

javascript - pjax 后页面重新加载

javascript - 如何从另一个表单组件更新书籍列表?

javascript - 使卡片和图像大小相同——我如何使用 CSS 做到这一点?