尽管传递了值,但 React 常量并未更新

时间:2021-07-24 13:24:21

标签: reactjs

我正在尝试改编 this 教程以从此网址获取数据:https://en.wikipedia.org/w/api.php?action=query&list=prefixsearch&format=json&pssearch=/ufc

请求正常运行并获得响应。但是,如果我执行 console.log(options);。控制台将选项变量显示为空。我做错了什么?

在类似且更具说明性的说明上,如果我执行以下操作。输出始终为 false

        setLoading(false);
        console.log(loading);
        setLoading(true);
        console.log(loading);
        setLoading(false);
        console.log(loading);

请求

import axios from 'axios';

const url = axios.create({
    baseURL: 'https://en.wikipedia.org/w/api.php?origin=*&action=query&list=prefixsearch&format=json&pssearch=',
    headers: {'Api-User-Agent':'EventGator (http://xxx.xxx.xxx.xxx:8080)'}
});

export const getApiSuggestions = (title) => {
    let result = url
        .get(`${title}`)
        .then((response) => {
            return response.data;
        })
        .catch((error) => {
            return error;
        });
    console.log(result);
    return result;
};

搜索页面

import React, {useContext, useState, useEffect} from "react";
import {SearchContext} from "../../contexts/SearchContext"
import { getApiSuggestions } from './requests';
import SearchInput from './SearchInput';
import { MainWrapper } from './style';
import "../../App.css"


export function Search (){

const [options, setOptions] = useState({matches:[]});
const [loading, setLoading] = useState(false);

const getSuggestions = async (title) => {
    if (title) {
        setLoading(true);
        let response = await getApiSuggestions(title);
        setOptions({matches:response.query.prefixsearch}); //This doesn't appear to save into options:matches

        setLoading(false);
        console.log(response.query.prefixsearch); //this provides the json result set to console.
        console.log(options);                     //this doesn't
    } else {
        setOptions([]);
    }
};

const getApiUrl = (url) => {
    window.open(url, '_blank');
};

    return (
      <div>
      <div className="search container">
      <div className="input-group input-group-sm mb-3 center">
            <MainWrapper className="form-control center">
                <SearchInput
                    loading={loading}
                    options={options}
                    requests={getSuggestions}
                    onClickFunction={getApiUrl}
                    placeholder="Search for a wikipedia title"
                />
            </MainWrapper>
            </div>
            </div>
      </div>
    );

}
export default Search;

输出:

console.log(response.query.prefixsearch)

[{ns: 0, title: "UFC 264", pageid: 67197876}, {ns: 0, title: "UFC Rankings", pageid: 55036039}, {ns: 0, title: "UFC on ESPN: Makhachev vs. Moisés", pageid: 67783350}, {ns: 0, title: "UFC 229", pageid: 56175506}, {ns: 0, title: "UFC 265", pageid: 67410930}, {ns: 0, title: "UFC 266", pageid: 67397733}, {ns: 0, title: "UFC on ESPN: Sandhagen vs. Dillashaw", pageid: 67577861}, {ns: 0, title: "UFC 257", pageid: 65611292}, {ns: 0, title: "UFC 205", pageid: 50527598}, {ns: 0, title: "UFC 200", pageid: 48625599}]

1 个答案:

答案 0 :(得分:0)

useStatesetState 是异步的,它们不会立即执行。

可以为此使用 Promises

const getSuggestions = (title = '') => {
        if (!title) { 
          return false
        }
        setLoading(true);
        getApiSuggestions(title)
           .then(response => 
             setOptions({ matches:response.query.prefixsearch });
           )
           .catch(error => {
              console.warn(error)
              return error
            })
           .finally(() => setLoading(false))
};