React componentDidMount获取API [英] React componentDidMount fetch api

查看:35
本文介绍了React componentDidMount获取API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在componentDidMount中获取一个api.api结果将设置为组件的状态,并将该状态映射并传递给子组件.

I am trying to fetch an api inside componentDidMount. The api result will be set to the component's state and the state mapped and passed to a children component.

如果我使用componentDidMount内部的 fetch方法获取api,则一切正常:

If I fetch the api using the fetch method inside the componentDidMount everything works fine:

componentDidMount(){
    fetch(apiToFetch)
        .then((result) => result.json())
        .then((result) => result.entries)
        .then((entries) => this.setState({ ...this.state, entries }))
        .catch((error) => console.log(error));
}

如果我在方法内部使用 fetch,然后在componentDidMount内部调用此方法,则不会呈现任何内容:

if I use fetch inside a method and then call this method inside componentDidMount nothing is rendered:

componentDidMount() {
    this.fetchApiToEntries(GLOBAL_PORTFOLIO_COLLECTION_API);
}

fetchApiToEntries(apiToFetch) {
    fetch(apiToFetch)
        .then((result) => result.json())
        .then((result) => result.entries)
        .then((entries) => this.setState({ ...this.state, entries }))
        .catch((error) => console.log(error));
}

我无法理解生命周期中缺少的内容.不应该采取以下措施吗?

I cannot understand what I am missing from the lifecycle. Shouldn't react do the following?

  • 初始化状态
  • 渲染
  • 致电componentDidMount
  • 渲染

这是我的最初组成部分:

Here is my initial component:

export default class Portfolio extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            entries: []
        }

    }
    componentDidMount() {

        this.fetchApiToEntries(GLOBAL_PORTFOLIO_COLLECTION_API);
    }
    fetchApiToEntries(apiToFetch) {
        fetch(apiToFetch)
            .then((result) => result.json())
            .then((result) => result.entries)
            .then((entries) => {
                this.setState({
                    ...this.state,
                    entries
                })
            })
            .catch((error) => console.log(error));
    }

    render() {

        return (
            <Fade bottom>
                <div className="Portfolio">
                    <div className="Portfolio__title"><h4 className="color--gradient text--spacing">WORKS</h4></div>
                    <OwlCarousel {...options}>
                        {this.state.entries.map((item) => (
                            <PortfolioElement item={item} />
                        ))}
                    </OwlCarousel>
                    <AnchorLink href='#contact'><Button className="contact-button btn--gradient slider-button Services__button">Let's get in touch</Button></AnchorLink>
                </div>
            </Fade>
        )
    }
}

PortfolioElement是未呈现的实际组件.有什么建议吗?谢谢.

PortfolioElement is the actual component not being rendered. Any advice? Thank you.

两种方法都无法以正确的方式重新呈现组件(...我没想到的事情:我不知道为什么,但是如果我在componentDidMount中两次调用它们,组件将呈现正确的方式).我想我在该州缺少一些东西.

both methods are not rerendering the component the right way (...something I didn't expect: I don't know why but if I call them twice in componentDidMount the component will render the right way). I think I am missing something in the state.

我在控制台中没有错误,这是我设置初始状态的方式:

I have no error in the console and this is how I set my initial state:

this.state={entries:[]}

这是控制台中的实际条目:

and this is what the actual entries looks like from the console:

 entries:
[0:{credits: "..."
    description: "..."
    featuredImage: {path: "portfolio/01.jpg"}
    firstImage: {path: "portfolio/firstimage.jpg"}
    secondImage: []
    slug: "..."
    tasks: (5) [{…}, {…}, {…}, {…}, {…}]
    title: "..."
    _by: "5beae6553362340b040001ee"
    _created: 1542123322
    _id: "5beaef3a3362340bf70000b4"
    _mby: "5beae6553362340b040001ee"
    _modified: 1542149308
},
1:{...}
]

提取后的状态是相同的.

My state after the fetch is the same way.

更新我发现问题是:当状态改变时,组件没有使用正确的道具重新渲染孩子.我通过道具传递了一个高阶组件中的API,并添加了componentWillUpdate方法来强制进行状态刷新以重新呈现该组件.这不是理想的解决方案,但是直到现在我还没有弄清楚其他方法.有什么建议吗?

UPDATE I figured out that the the problem is: when the state changes the component is not rerendering the child with the correct props. I called the API in an higher order component passed down the props and added a componentWillUpdate method forcing a state refresh that rerenders the component. Not the ideal solution but I am not figuring out other ways until now. Any advice?

推荐答案

知道您的api响应是什么,但我使用伪造的API测试了您的代码并进行了更改

Idk what your api response is but I tested your code with a fake API and changed

fetchApiToEntries(apiToFetch){}

到箭头函数(并且工作正常.

完整示例:



    export default class Portfolio extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
                entries: []
            }
        }
        componentDidMount() {
          this.fetchApiToEntries('https://jsonplaceholder.typicode.com/posts');
        }
        fetchApiToEntries = (apiToFetch) => {
            fetch(apiToFetch)
                .then(result => result.json())
                .then((entries) => {
                    this.setState({
                        ...this.state,
                        entries
                    })
                })
                .catch((error) => console.log(error));
        }
        render() {
          const {entries} = this.state;
            console.log(entries);
            return (
                // Everything you want to render.
            )
        }
    }

希望它对您有帮助.

这篇关于React componentDidMount获取API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆