简体   繁体   English

JSON.stringify 返回“”反应

[英]JSON.stringify returns “” React

React/Js newbie here. React/Js 新手在这里。

I have a fairly simple crypto api fetch:我有一个相当简单的加密 api 获取:

import React from 'react';
import axios from 'axios';
import './data.css';

function App() {
  let [responseData, setResponseData] = React.useState('');

  const fetchData = React.useCallback(() => {
    axios({
      "method": "GET",
      "url": "https://rest.coinapi.io/v1/exchangerate/BTC/USD",
      "headers": {
        "X-CoinAPI-Key": process.env.REACT_APP_API_KEY
      }
    })
    .then((response) => {
      console.log(response.data);
      setResponseData(responseData);

    })
    .catch((error) => {
      console.log(error)
    })
  }, [responseData])

  React.useEffect(() => {
    fetchData()
  }, [fetchData])

  return (
    <div className='main'>
      <div className="App">
      <header className="App-header">
        <h1>
          Fetching Data with React Hooks
        </h1>
        <button type='button' onClick={fetchData}>Click for Data</button>
      </header>
      <pre>{JSON.stringify(responseData)}</pre>
    </div>
    </div>
  );
}

export default App;

This is the result这是结果结果页面

Where the double quotes are """" my intended result is to print the json object shown in the console log.双引号是 """" 我的预期结果是打印控制台日志中显示的 json object。 The console is logging the intended response:控制台正在记录预期的响应:

{
  "time": "2021-02-10T03:36:21.6225472Z",
  "asset_id_base": "BTC",
  "asset_id_quote": "USD",
  "rate": 46389.408377086196898279013665
}

This looks like it might just be a typo.这看起来可能只是一个错字。 You need to replace setResponseData(responseData) with setResponseData(response.data) .您需要将setResponseData(responseData)替换为setResponseData(response.data)

You said you are begginer, so I wanted to show some stuff that might help along the way...你说你是初学者,所以我想展示一些可能会有所帮助的东西......

import React, {useEffect, useState} from 'react';
import axios from 'axios';
import './data.css';

const fetch = () => axios({
      "method": "GET",
      "url": "https://rest.coinapi.io/v1/exchangerate/BTC/USD",
      "headers": {
        "X-CoinAPI-Key": process.env.REACT_APP_API_KEY
      }
    })
    .then(resp => resp.data)

function App() {
  const [responseData, setResponseData] = useState('');
  
  const doFetch = () => fetch()
    .then(setResponseData)
    .catch(console.log)
  
  useEffect(doFetch, []); //only needed if you fetch on first render

  return (
    <div className='main'>
      <div className="App">
      <header className="App-header">
        <h1>
          Fetching Data with React Hooks
        </h1>
        <button type='button' onClick={doFetch}>Click for Data</button>
      </header>
      <pre>{JSON.stringify(responseData)}</pre>
    </div>
    </div>
  );
}

export default App;

I could not test all this, but should work.我无法测试所有这些,但应该可以。

Put fetch logic outside the component so it could be extracted to other file and unit tested.将获取逻辑放在组件之外,以便可以将其提取到其他文件并进行单元测试。

You can use const in useState destructuring, both are immutable.您可以在 useState 解构中使用 const,两者都是不可变的。

Used point-free to simplify doFetch logic.使用无点来简化 doFetch 逻辑。

useEffect is only needed if you want to fetch on first render, before any button clicks.仅当您想在第一次渲染时,在单击任何按钮之前获取 useEffect 才需要。

removed the useCallback, probably too much complexity for something that simple... couldn't see the necessity to use memoization here, but maybe your response is giant and I'm wrong...删除了useCallback,对于这么简单的事情可能太复杂了......在这里看不到使用记忆的必要性,但也许你的反应是巨大的,我错了......

I believe our friends in the comments had already awnsered your question, so I wanted to show some different style of coding the same thing, for you to have another example...我相信评论中的朋友已经回答了你的问题,所以我想展示一些不同风格的编码相同的东西,让你有另一个例子......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM