首页 > 解决方案 > 状态更改时我无法获得 API 响应

问题描述

我构建了一个从电影 API 中提取数据的简单应用程序。当用户在输入中键入内容时,状态 URL 应使用输入中的值进行更新。在单击按钮之前一切正常(“hendleSubmit”方法被调用)并且我看到我的错误消息“出现错误类型错误:尝试获取资源时出现网络错误。” 有人可以帮我解决这个问题吗?

这是我的 Codepen 的链接

class App extends React.Component{
  constructor(props){
    super(props);
    
     this.state = {
       data: [],
       url: ""
     } 
    }
  // Method to call APIs
   getApiResponse() {
     console.log(this.state.url);
    fetch(this.state.url)
            .then(result => result.json())
            .then(result => {
        const results = result["Search"];
             this.setState({
                    data: results
                })
       console.log("Data result: " + results);
            })
      .catch(error => {
        console.log('Something went wrong ' + error);
      })
   }
    componentDidMount(){ 
      console.log("The Form component has been mounted");
    }
  
  handleChange = (event) => {
    const {value} = event.target;
    event.preventDefault();
    this.setState({
      url: 'https://www.omdbapi.com/?apikey=thewdb&s=' + value
    })
  }   
  handleSubmit = () => {
    return this.getApiResponse();
    }

  render(){
    console.log("STATE URL: " + this.state.url);
    const { data } = this.state;

    return(
    <div className="container">
        <h3 className="text-center">Test Page</h3>
        <Table movieData={data}/>
        <Form handleChange={this.handleChange}
              handleSubmit={this.handleSubmit} />
    </div>
    )
  }
}

class Table extends React.Component{
  render(){
    const {movieData} = this.props;
    return(
    <table className="table table-dark table-hover">
      <TableHeader />
      <TableBody movieData={movieData} />  
    </table>  
    )
  }
}
class Form extends React.Component{
  render(){
    const { handleChange, handleSubmit } = this.props;
    return(
     
    <form action="" method="" className="form-inline">
    <input name="movieName" type="text" placeholder="Enter search" onChange={handleChange}/>
    <button type="submit" className="btn btn-outline-primary" onClick={handleSubmit}>search</button>
    </form>
   
    )
  }
}

const TableHeader = () => {
  return(
  <thead>
      <tr>
        <th>Title</th>
        <th>Year</th>
        <th>ID</th>
      </tr>
    </thead>
  )
}

const TableBody = (props) => {
  const rows = props.movieData.map((row, index) => {
    console.log(row);
    return(
      <tr key={index}>
        <td>{row.Title}</td>
        <td>{row.Year}</td>
        <td>{row.imdbID}</td>
      </tr>  
    )
  })
  
  return(
  <tbody>{rows}</tbody>
  )
}
ReactDOM.render(<App />, document.getElementById("root"));
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Anton App</title>
   <link href="https://fonts.googleapis.com/css?family=Dosis:400,700" rel="stylesheet">
    <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
    </head>
<body>
  <div id="root"></div>
</body>

标签: reactjs

解决方案


您需要阻止默认的 onSubmit 操作。您的问题是,在您发起请求后,默认表单提交操作会运行并重新加载您的页面。

将 handleSubmit 更改为如下所示:

handleSubmit = ev => {
  ev.preventDefault(); // prevent form submission
  return this.getApiResponse();
}

推荐阅读