【问题标题】:How to use fetch and call rest api如何使用 fetch 和调用 rest api
【发布时间】:2021-12-24 12:41:27
【问题描述】:

如何在上面的代码中添加fetch 我试图在 setEffect 中使用 fetch 调用 rest API,但出现错误。

目标:在我提交表单时调用其余 API。 到目前为止,我能够从表单动态生成 URL,并且无法连接以获取和调用其余 API。

const { useState } = React;

function Example() {

  const [ form, setForm ] = useState({});

  function handleSubmit() {
    const uri = `http://example.com/?${form.one}&${form.two}`;
    console.log(`Current state: ${JSON.stringify(form)}`);
    console.log(`Fetch URI: ${uri}`);
    // fetch(uri)... etc
  }


  function handleChange(e) {
    const { nodeName, name, value } = e.target;
    if (nodeName === 'INPUT') {
      setForm({ ...form, [name]: value });
    }
  }

  return (
    <form onChange={handleChange}>
      <fieldset>
        <legend>Input one</legend>
        <input name="one" value={form.one} />
      </fieldset>
      <fieldset>
        <legend>Input two</legend>
        <input name="two" value={form.two} />
      </fieldset>
      <button type="button" onClick={handleSubmit}>Submit</button>
    </form>
  );
};

ReactDOM.render(
  <Example />,
  document.getElementById('react')
);

【问题讨论】:

  • 首先,onChange 应该在输入元素上,而不是在表单上。你应该制作按钮type="submit"。您应该在表格中添加onSubmit={handleSubmit}。在handleSubmit 内,您应该添加事件并防止默认行为handleSubmit(e) { e.preventDefault(); ... }。既然已经不碍事了,你有没有查过如何做一个获取请求?您是否查看过如何从该获取请求中设置状态值?

标签: reactjs rest react-hooks fetch flask-restful


【解决方案1】:

首先,onChange 应该在输入元素上,而不是在表单上。你应该使按钮类型=“提交”。您应该在表单上添加 onSubmit={handleSubmit} 。在 handleSubmit 你应该添加事件并防止默认行为 handleSubmit(e) { e.preventDefault(); ... }。

然后您可以在 handleSubmit 中调用您的 fetch api。

        const { useState } = React;
        
        function Example() {  
               const [ form, setForm ] = useState({one:'',two:''});
                function handleSubmit(e) {
                    e.preventDefault();
                    const uri = `http://example.com/?$one=
{form.one}&tow=${form.two}`;
                    fetch(uri, {
                        method: 'POST', // *GET, POST, PUT, DELETE, etc.)
                        body: JSON.stringify(form),
                    }).then(r=>{
                        console.log(r)
                    })
                    // console.log(`Current state: ${JSON.stringify(form)}`);
                    // console.log(`Fetch URI: ${uri}`);
                    // fetch(uri)... etc
                }
            
            
                function handleChange(e) {
                    const { nodeName, name, value } = e.target;
                    if (nodeName === 'INPUT') {
                        setForm({ ...form, [name]: value });
                    }
                }
              return (
                <div >
                    <form onChange={handleSubmit}>
                        <fieldset>
                            <legend>Input one</legend>
                            <input name="one" value={form.one} onChange={handleChange}/>
                        </fieldset>
                        <fieldset>
                            <legend>Input two</legend>
                            <input name="two" value={form.two} onChange={handleChange}/>
                        </fieldset>
                        <button type="button" onClick={handleSubmit}>Submit</button>
                    </form>
                </div>
              );
    };
    
    ReactDOM.render(
      <Example />,
      document.getElementById('react')
    );

这对我很有效。

【讨论】:

  • 获得 400(错误请求)
  • 当你创建一个类似 :example.com/?${form.one}&${form.two} 的 uri 或者你输入 example.com/?one=${form.one}&tow=${form.two}
  • 如果问题与payload无关,请检查查询uri
  • @harsh 所以你的 API 有问题,而不是反应。
  • @Samira https://flask-api-test1.herokuapp.com/predict?solute=${form.one}&amp;solvent=${form.two} 这是我使用的 api
猜你喜欢
  • 1970-01-01
  • 2021-09-03
  • 1970-01-01
  • 2012-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多