首页 > 解决方案 > 获取请求未更新状态

问题描述

我有一个连接到数据库的反应应用程序。目前,应用程序在挂载时获取数据库并使用它来填充状态。这些应用程序允许某人发布到数据库。到目前为止,这行得通。

问题是我希望用户看到新发布的内容。因为它是仅在我重新加载页面后才会填充的内容。我试图在 POST 请求之后运行的函数中重复 componentDidMount() 中的编码,但由于某些原因不起作用。

class App extends Component {
    state = {
        notes: [],
        folders: [],
        //noteID: 0,
        //folderID: 0
    };

    componentDidMount() {
        Promise.all([
          fetch(`${config.API_ENDPOINT}/notes`),
          fetch(`${config.API_ENDPOINT}/folders`)
        ])
          .then(([notesRes, foldersRes]) => {
            if (!notesRes.ok)
              return notesRes.json().then(e => Promise.reject(e))
            if (!foldersRes.ok)
              return foldersRes.json().then(e => Promise.reject(e))
    
            return Promise.all([
              notesRes.json(),
              foldersRes.json(),
            ])
          })
          .then(([notes, folders]) => {
            this.setState({ notes, folders })
          })
          .catch(error => {
            console.error({ error })
          })
      }

    pageReload = () =>{
        //console.log('pageReload ran');

        Promise.all([
            fetch(`${config.API_ENDPOINT}/notes`),
            fetch(`${config.API_ENDPOINT}/folders`)
          ])
            .then(([notesRes, foldersRes]) => {
              if (!notesRes.ok)
                return notesRes.json().then(e => Promise.reject(e))
              if (!foldersRes.ok)
                return foldersRes.json().then(e => Promise.reject(e))
      
              return Promise.all([
                notesRes.json(),
                foldersRes.json(),
              ])
            })
            .then(([notes, folders]) => {
              this.setState({ notes, folders })
            })
            .catch(error => {
              console.error({ error })
            })
    }
    
    folderSubmit = (f) => {
        //console.log("folderSubmit ran " + f);

        const newFolder = { "name" : f };

        const postfolder = {
            method: 'POST',
            headers: {
                'content-type': 'application/json'
              },
            body: JSON.stringify(newFolder)
        };

        fetch(`${config.API_ENDPOINT}/folders`, postfolder).then(this.pageReload())

    }

标签: reactjsgetfetch

解决方案


看起来你在发布后没有设置你的状态。请参阅下面您需要设置状态的位置。

folderSubmit = (f) => {
        //console.log("folderSubmit ran " + f);

        const newFolder = { "name" : f };

        const postfolder = {
            method: 'POST',
            headers: {
                'content-type': 'application/json'
              },
            body: JSON.stringify(newFolder)
        };

        fetch(`${config.API_ENDPOINT}/folders`, postfolder)  
    .then(response => response.json())
    .then(data => this.setState(data));

    }

推荐阅读