javascript - 在 React 中使用 Hooks 获取 JSON 的正确方法是什么?

标签 javascript reactjs state react-hooks react-state

所以我有这个应用程序,它显示从 API 中作为 JSON 数据提取的随机引号。这是我第一次尝试 React,所以做得还不是很好。最初,我将所有代码存储在一个组件中 - 但这显然不是最佳实践,因为我有多个可以拆分为组件的内容,即引用、页脚、共享按钮。

我在拆分它时遇到的问题是,我不知道如何在组件文件之间共享状态(用于共享到 Twitter 或其他附加功能),因为我像这样获取数据:

/* this function accesses the API and returns a json */
export default function fetchQuote() {
    return fetch('https://programming-quotes-api.herokuapp.com/quotes/random') // fetch a response from the api
        .then((response) => { 
            let json = response.json(); // then assign the JSON'd response to a var
            return json; // return that bad boy
    });
}

最初是在组件类中调用的,如下所示:

/* component for the quotes */
export default class Quote extends React.Component {
    /* placeholder */
    constructor(props) {
        super(props);
        this.state = {
            quoteAuthor: "Rick Osborne", 
            quote: "Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live."
        }
    }
    /* actually render things */
    render() {
        return (
            <div className="quotes">
                <h1>{this.state.quoteAuthor}</h1>
                <p>{this.state.quote}</p>
                <div className="button">
                    <button id="button" onClick={this.update}>New quote</button>
                </div>
            </div>
        );
    }

    /* async fetch the quotes and reassign the variables to them once processed */
    update = async() => {
        let response = await fetchQuote();
        console.log(response);
        this.setState({
            quoteAuthor: response.author,
            quote: response.en
        });
    };   
}

根据我的理解,React 的钩子(Hook)似乎解决了我的问题,因为我可以使用 useStateuseEffect ,我尝试按如下方式实现(使用原始的 fetchQuote () 函数不变):

export default function Quote() {
    const [author, setAuthor] = useState("Rick Osborne");
    const [quote, setQuote] = useState(
        "Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live."
        );
    let json = fetchQuote();

    useEffect (() => {
        setAuthor(json.author);
        setQuote(json.quote);
        console.log(json);
    });

    return (
        <div className="quotes">
            <h1>{author}</h1>
            <p>{quote}</p>
            <div className="button">
                <button id="button" onClick={async () => json = await fetchQuote()}>
                    New quote
                </button>
            </div>
        </div>
    )
}

但是,除了显示引用的区域显示为空并且在 useEffect 中调用 console.log(json) 只是返回

之外,不会引发任何错误>
Promise { <state>: "pending" }
Promise { <state>: "pending" }

我是否正确使用了 Hooks?如何使用 JSON 数据正确更新状态?

最佳答案

看起来来自 fetch 的 promise 没有得到解决。 试试这个:

export default Quote = () => {
    const [author, setAuthor] = useState("Rick Osborne");
    const [quote, setQuote] = useState('');

    const fetchMyAPI = async () => {
      let json = await fetchQuote();
      setAuthor(json.author);
      setQuote(json.quote);
    }

    useEffect(() => {
     fetchMyAPI();
    }, []);

    return (
        <div className="quotes">
            <h1>{author}</h1>
            <p>{quote}</p>
            <div className="button">
                <button id="button" onClick={fetchMyAPI}>
                    New quote
                </button>
            </div>
        </div>
    )

这称为 fetchMyAPI onMount,并在您单击New Quote时调用它。

关于javascript - 在 React 中使用 Hooks 获取 JSON 的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60610256/

相关文章:

javascript - 当元素没有设置类名时的 DOM HTMLElement className 属性

javascript - react-router 在每次转换时滚动到顶部

javascript - 如何使用带有 expo 的 React-Navigation 正确键入作为 Prop 传递的导航

Cocoa:如何将 bool 属性绑定(bind)到 NSCellStateValue?

javascript - 导出模块并在导入时抛出错误/停止执行

c# - 如何将服务器端属性值传递到 aspx 页面框架中加载的其他 htm 页面

javascript - 如何在 Jquery if 语句中使用随机数计数器

javascript - 根据 url 中给出的值,使用 React 路由动态渲染 React 组件

javascript - 将 props/state 传递给父组件/从父组件传递

android - 当列表项属性在其 DetailsActivity 中更改时维护列表项状态?