简体   繁体   English

使用axios响应来响应JSX渲染

[英]React JSX rendering with axios response

I need to ask this question because tried to fix that issue couple of hours. 我需要问这个问题,因为试图在几个小时内解决该问题。 Now I created a simple layout and this is has a sidebar. 现在,我创建了一个简单的布局,它具有一个侧边栏。 There is a navigation in this block. 此块中有一个导航。 I'm trying to get list of coins and iterate them in to list element. 我正在尝试获取硬币列表并将其迭代到list元素中。

sidebar.jsx sidebar.jsx

export default {

    Sidebar() {
        return (
            <div>
                <h3>Coins</h3>
                {
                    axios({
                        method: "GET",
                        url: "./ticker.json",
                    }).then(function (resp) {

                        let list = resp.data;
                        return Object.keys(list).map((key) => {
                            console.log(list[key].name);
                            return (<li key={key}>{list[key].name}</li>)
                        });

                    }).catch(function (errors) {

                        alert("Error thrown");
                    })
                }
            </div>
        )
}

I imported that sidebar.jsx in App.js , you can see whole App.js below 我将sidebar.jsx导入App.js ,您可以在下面看到整个App.js

import Landing from './views/landing';
import Header from './components/header';
import Sidebar from './components/sidebar';

function App() {
    return (
        <div className="container-fluid">
            {Header()}
            <div className="row">
                <div className="col-md-2">
                    {Sidebar.Sidebar()}
                </div>
                <div className="col-md-10">
                    {Landing(logo)}
                </div>
            </div>

        </div>
    );
}

export default App;

I'm getting below error. 我遇到错误了。 I can't understand how to fix it. 我不明白该如何解决。

Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.

I know axios return Promise but I don't understand how to handle it. 我知道axios返回Promise但我不知道该如何处理。 If someone could help me, that I'll much appreciated. 如果有人可以帮助我,我将不胜感激。

Imperative code inside functional components must go inside useEffect or similar custom hooks. 功能组件内部的命令性代码必须放入useEffect或类似的自定义挂钩中。 You could store the response in a state variable. 您可以将response存储在state变量中。 And render only when the data get's resolved. 并且仅在解析data后才渲染。

const App = () =>{
    const [data, setData] = useState(null)

    useEffect(() =>{
        axios.get(url)
            .then(res => setData(res.data))
    },[])


    return(
        <div>
           {
            data &&  Object.keys(data).map((key) => {
               console.log(list[key].name);
               return (<li key={key}>{list[key].name}</li>)
            })
            }
        </div>
    )
} 

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

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