简体   繁体   中英

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.

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

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. If someone could help me, that I'll much appreciated.

Imperative code inside functional components must go inside useEffect or similar custom hooks. You could store the response in a state variable. And render only when the data get's resolved.

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>
    )
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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