【问题标题】:Displaying JSON data on front-end using fetch使用 fetch 在前端显示 JSON 数据
【发布时间】:2020-04-15 12:46:24
【问题描述】:

这里对 React 来说真的很新,我想做一个简单的搜索框,用户在其中提交“问题”,JSON 返回“结果”的值。

请求通过,我得到了响应,唯一我找不到的就是从中获取结果并将它们显示在前端。

class Search extends Component {
    state = {
      searchValue: "",
      searchSection: "",
      results: [],
      // section: []
    };

    handleOnChange = event => {
      this.setState({ searchValue: event.target.value });
    };

    handleSearch = () => {
      this.makeApiCall(this.state.searchValue);
    };

    makeApiCall() {
      fetch("http://example.com/json", {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            question: (this.state.searchValue),
            section: (this.state.searchSection),
        })
    })

        .then((response) => response.json())

        .then((responseData) => {
          console.log(
            "POST Response",
            "Response Body -> " + JSON.stringify(responseData)
          )
            return responseData
        })
      .then(results => this.setState({results: results.value}))
    };

    render() {
      return (
        <div id="main" className="py-16">
          <label className="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2" for="grid-first-name">
              Ask a question
          </label>
          <input
            name="text"
            type="text"
            placeholder=""
            onChange={event => this.handleOnChange(event)}
            value={this.state.searchValue}
            className="shadow-sm appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
          />
          <button onClick={this.handleSearch} className="cursor-pointer mt-5 bg-white hover:bg-gray-100 text-gray-800 font-semibold py-2 px-4 border border-gray-400 rounded-full shadow">Search</button>

          // DISPLAYING THEM ON THE FRONT HERE
          {this.state.results ? (
            <div id="question-container">
              {this.state.results.map((result) => (
                <div className="result">
                  <h2>{result.title}</h2>
                  <p>{result.sentences}</p>
                </div>
              ))}

            </div>
          ) : (
            <p>Can't find results for your question</p>
          )}
        </div>
      );
    }
  }

  export default Search;

我的 JSON 是这样的:

{
  "request": {
    "date_from": "", 
    "date_to": "", 
    "question": "User question here", 
    "section": null
  }, 
  "results": {
    "docs": [
      {
      "title": " "
      "section": " "
   }
  ]
 }
}

我需要显示来自 JSON 的多个问题

【问题讨论】:

    标签: json reactjs fetch gatsby


    【解决方案1】:

    makeApiCall 中,将results.value 更改为results.docs,因为您的JSON 具有docs 属性,其中包含您要显示的所有数据。

    makeApiCall() {
          fetch("http://example.com/json", {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                question: (this.state.searchValue),
                section: (this.state.searchSection),
            })
        })
    
            .then((response) => response.json())
            .then((responseData) => {
              console.log(
                "POST Response",
                "Response Body -> " + JSON.stringify(responseData)
              )
                return responseData
            })
          .then(results => {
              this.setState({
               results: results.docs
              },()=>console.log(this.state)) 
          })
        };
    

    【讨论】:

    • 谢谢萨塔克!我仍然收到“找不到您的问题的结果”的回复,但在{this.state.results ? ( &lt;div id="question-container"&gt; {this.state.results.map((result) =&gt; ( &lt;div className="result"&gt; &lt;h2&gt;{result.title}&lt;/h2&gt; &lt;p&gt;{result.sentences}&lt;/p&gt; &lt;/div&gt; ))} &lt;/div&gt; ) : ( &lt;p&gt;Can't find results for your question&lt;/p&gt; )} 中获得回复时一定有问题
    • setState 之后检查您的状态一次。也更新了相同的代码。
    • error Parsing error: Unexpected token, expected ",":/
    • 缺少一个 ')' @KostasVrouvas
    • 不幸的是它不起作用....在控制台中我得到results: undefined ​ searchSection: "" ​ searchValue: "" 并且答案容器div没有显示结果。相反,我得到了没有结果的 div。我最初遵循这个:github.com/lytes20/meal-search-app 并重新组织它以获取 POST 请求。但是“渲染”部分似乎有问题......
    【解决方案2】:

    因此,在 Sarthak Aggarwal 和 Bamuleseyo Gideon(感谢 Gideon)的帮助下,我找到了解决方案。

    实际的问题是我没有针对 Sarthak 所说的正确属性。但是results.docs也是错误的。

    所以,而不是

    .then(results =&gt; this.setState({results: results.value}))

    我改成

      .then(jsonData => {
        this.setState({ docs: jsonData.results.docs });
      });
    ``
    
    and it works like a charm :)
    

    【讨论】:

      猜你喜欢
      • 2021-12-11
      • 2023-04-09
      • 2018-11-26
      • 2018-09-19
      • 1970-01-01
      • 2022-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多