如何使用post将server.js中的React组件呈现给App.js?


polo
2025-01-29 06:30:34 (1月前)
  1. 我是ReactJavascript的初学者,所以还在学习:)

我正在创建一个神奇的8球应用程序,一旦单击按钮,使用post方法,我想返回一个随机的答案(其中一个…

3 条回复
  1. 0# 真不错 | 2019-08-31 10-32



    这种东西很好地解释了

    文档




    每次执行API请求时都需要使用state,因为它是一种副作用。我建议您阅读文档并理解它,但要使其在您的组件中工作,请在组件的开头添加:




    1. class BlaBla extends Component {
      state = {
      response: undefined
      };

    2. /* Rest of component code */
    3. }

    4. </code>


    并将您的获取请求更改为如下所示:




    1. fetch(‘/‘, { method: POST }).then(response => this.setState({response}));

    2. </code>


    通过添加状态,您也会遇到绑定问题,因此将方法声明更改为箭头函数,由此:




    1. handleSubmit(event) { / code / }

    2. </code>


    对此:




    1. handleSubmit = (event) => { / code / }

    2. </code>


    要在答案段落中显示结果,请执行以下操作:




    1. Answer: {this.state.response}

    2. </code>

  2. 1# 电动少女 | 2019-08-31 10-32


    基本上,您需要将获取调用的结果保存到组件状态。使用setState,它将自动触发组件的重新呈现并显示新的答案。



    试试这个:




    1. handleSubmit(event) {
      event.preventDefault();
      // assuming the fetch works ok…
      fetch(‘/‘, { method: POST }).then(response =>
      response.json().then(data => this.setState({answer:response}) )
      )
      }




    然后在render()里面:





    1. Answer:{this.state.answer}


      Question count: {this.state.count}


    2. </code>


    编辑:



    您可能需要将响应解析为json,例如




    1. fetch(‘/‘, { method: POST }).then(response =>
      this.setState({answer:JSON.parse(response)})
      )

    2. </code>

登录 后才能参与评论