0

尝试获取数据的代码:

class Search extends Component {
  state = {
    bookList: [],
    bookk: "",
    search: [],
    searchResults: [],
    isLoading: true,
    isError: false,
    searchQuery: "",
  }
  /**
   * React lifecycle method to fetch the data
   */
  async componentDidMount() {
    Axios.get('http://localhost:8000/hentObjekterJSON/Studium')
      .then(result => {
        const bookData = result.data
        bookk = result.data
        this.setState({ bookList: bookData.Studium})
        this.rebuildIndex()
      })
      .catch(err => {
        this.setState({ isError: true })
        console.log("====================================")
        console.log(`Something bad happened while fetching the data\n${err}`)
        console.log("====================================")
      })
  }

JSON响应:

{"Studium": {"studiumkode": "ABIOK", "studium": "ABIOK (anestesi/barnevern/intensiv/operasjon/kreftsykepleie"}}

bookList 和 bookk 似乎都没有分配数据。

我已经检查并且 URL 正在提供 JSON(作为 JsonResponse))为什么 Axios 找不到并使用数据?

4

1 回答 1

0

一些建议的指针...

class Search extends Component {
    state = {
        bookList: [],
        bookk: "",
        search: [],
        searchResults: [],
        isLoading: true,
        isError: false,
        searchQuery: "",
    }

/**
    * React lifecycle method to fetch the data
*/

// Not sure you need async on the below line
async componentDidMount() {
    Axios.get('http://localhost:8000/hentObjekterJSON/Studium')
    .then(result => {

        const bookData = result.data
        console.log(bookData) // Actually see what is returned.

        // You may need to parse the data....
        const bookData = JSON.parse(result.data)

        bookk = result.data // This should a 'setState'.

        this.setState({ bookList: bookData.Studium,
                        bookk: result.data})

        // setState is async, so rebuild might run before setState has finished.
        this.rebuildIndex()

        // If you want something to run only once set state has completed, then try
        this.setState({ bookList: bookData.Studium,
                        bookk: result.data}, this.rebuildIndex())
    })
    .catch(err => {
        this.setState({ isError: true })
        console.log("====================================")
        console.log(`Something bad happened while fetching the data\n${err}`)
        console.log("====================================")
    })
}
于 2020-03-20T11:55:24.057 回答