Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 提交表单后如何在React.js中更新DOM_Reactjs_Forms - Fatal编程技术网

Reactjs 提交表单后如何在React.js中更新DOM

Reactjs 提交表单后如何在React.js中更新DOM,reactjs,forms,Reactjs,Forms,我的应用程序应该显示注释,并允许用户通过提交表单来添加注释。当我提交表单时,我没有从我的函数中获得控制台日志,该函数从服务器获取所有帖子。但是,当我刷新页面或忽略event.preventDefault()时,它会显示最新的帖子。如何确保getAllNotes()在成功发布到服务器后运行 class App extends Component { constructor(props) { super(props); this.state = { allNotes:

我的应用程序应该显示注释,并允许用户通过提交表单来添加注释。当我提交表单时,我没有从我的函数中获得控制台日志,该函数从服务器获取所有帖子。但是,当我刷新页面或忽略event.preventDefault()时,它会显示最新的帖子。如何确保getAllNotes()在成功发布到服务器后运行

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      allNotes: [],
      title: "",
      body: ""
    };
  }

  getAllNotes() {
    axios
      .get("http://localhost:5000/allnotes")
      .then(res => {
        const allNotes = res.data;
        console.log("res.data ", res.data);
        this.setState({ allNotes });
      })
      .catch(err => {
        console.error(err);
      });
  }

  // update state based on name of input
  handleChange = event => {
    this.setState({ [event.target.name]: event.target.value });
  };

  handleSubmit = event => {
    event.preventDefault();
    const { title, body } = this.state;
    const time = moment(Date.now()).format("YYYY-MM-DD HH:mm:ss");

    axios
      .post("http://localhost:5000/addnote", { title, body, time })
      .then(result => {
        this.getAllNotes();
      })
      .catch(err => {
        console.error(err);
      });

    // this.props.history.push("/");
  };

  deleteNote(id) {
    // <-- declare id parameter
    axios
      .delete(`http://localhost:5000/delete/${id}`) // <-- remove ;
      .then(() => {
        // Issue GET request after item deleted to get updated list
        // that excludes note of id
        this.getAllNotes();
      })
      .then(res => {
        const allNotes = res.data;
        this.setState({ allNotes });
      });
  }

  componentDidMount() {
    this.getAllNotes();
  }

  render() {
    const { allNotes, title, body } = this.state;
    return (
      <div className="App">
        <Switch>
          <Route
            exact
            path="/"
            render={() => (
              <Home allNotes={allNotes} deleteNote={this.deleteNote} />
            )}
          />
          <Route
            path="/AddNote"
            render={() => (
              <AddNote
                title={title}
                body={body}
                handleChange={this.handleChange}
                handleSubmit={this.handleSubmit}
              />
            )}
          />
          <Route path="/EditNote" render={() => <EditNote />} />
        </Switch>
      </div>
    );
  }
}
类应用程序扩展组件{
建造师(道具){
超级(道具);
此.state={
所有注释:[],
标题:“,
正文:“”
};
}
getAllNotes(){
axios
.get(“http://localhost:5000/allnotes")
。然后(res=>{
const allNotes=res.data;
console.log(“res.data”,res.data);
this.setState({allNotes});
})
.catch(错误=>{
控制台错误(err);
});
}
//根据输入的名称更新状态
handleChange=事件=>{
this.setState({[event.target.name]:event.target.value});
};
handleSubmit=事件=>{
event.preventDefault();
const{title,body}=this.state;
常量时间=时刻(Date.now()).format(“YYYY-MM-DD HH:MM:ss”);
axios
.post(“http://localhost:5000/addnote“,{标题、正文、时间})
。然后(结果=>{
这是.getAllNotes();
})
.catch(错误=>{
控制台错误(err);
});
//this.props.history.push(“/”);
};
删除注释(id){
//  {
const allNotes=res.data;
this.setState({allNotes});
});
}
componentDidMount(){
这是.getAllNotes();
}
render(){
const{allNotes,title,body}=this.state;
返回(
(
)}
/>
(
)}
/>
} />
);
}
}
从“React”导入React;
从“反应引导/Navbar”导入Navbar;
从“react router dom”导入{Link};
const AddNote=({title,body,handleChange,handleSubmit})=>{
返回(
Notes应用程序
添加注释
标题
注
);
};
导出默认的AddNote;

您能显示
主页
组件
的代码吗

Home
可能只在初始化时显示其注释(即,只有在Home的构造函数中,Home才将其
allNotes
props设置为其状态),这可以解释为什么在查看最新帖子之前需要刷新页面


顺便说一句:我想你不小心复制并粘贴了两次
应用程序
代码类(但是对于重复的
应用程序
代码,你可以编辑它使其成为
主页
代码:)

你能显示
主页
组件的代码吗

Home
可能只在初始化时显示其注释(即,只有在Home的构造函数中,Home才将其
allNotes
props设置为其状态),这可以解释为什么在查看最新帖子之前需要刷新页面


顺便说一句:我想你不小心复制并粘贴了两次
应用程序
代码类(但是对于重复的
应用程序
代码,你可以编辑它使其成为
主页
代码:)

你不需要担心“如何更新DOM”。React会为你做这件事。无论何时道具或状态发生更改,React都将使用新值重新渲染组件。唯一的例外是pureComponents,如果新的道具和状态与以前的道具和状态完全相同,它将不会重新渲染


在发布到新便笺后,能否确认getAllNotes回调正在触发?它在刷新后工作的事实只意味着componentDidMount按预期工作。

您不必担心“如何更新DOM”。React会为你做这件事。无论何时道具或状态发生更改,React都将使用新值重新渲染组件。唯一的例外是pureComponents,如果新的道具和状态与以前的道具和状态完全相同,它将不会重新渲染


在发布到新便笺后,能否确认getAllNotes回调正在触发?它在刷新后工作的事实只意味着componentDidMount正在按预期工作。

您完全正确,这是服务器端的错误您完全正确,这是服务器端的错误
import React from "react";
import Navbar from "react-bootstrap/Navbar";
import { Link } from "react-router-dom";
const AddNote = ({ title, body, handleChange, handleSubmit }) => {
  return (
    <div>
      <Navbar>
        <Navbar.Brand>
          <Link to="/" style={{ textDecoration: "none" }}>
            Notes App
          </Link>
        </Navbar.Brand>
      </Navbar>
      <h1>Add Note</h1>
      <form onSubmit={handleSubmit}>
        <div className="form-group">
          <label>
            Title
            <input
              type="text"
              className="form-control"
              name="title"
              placeholder="Title"
              value={title}
              onChange={handleChange}
            />
          </label>
        </div>
        <div className="form-group">
          <label>
            Note
            <textarea
              className="form-control"
              name="body"
              rows="3"
              value={body}
              onChange={handleChange}
            />
          </label>
        </div>
        <input type="submit" value="Submit" />
      </form>
    </div>
  );
};
export default AddNote;