首页 > 解决方案 > React componentDidMount 获取 api

问题描述

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

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

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 中调用此方法,则不会呈现任何内容:

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

我无法理解我在生命周期中缺少什么。不应该做出以下反应吗?

这是我的初始组件:

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 是未呈现的实际组件。有什么建议吗?谢谢你。

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

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

this.state={entries:[]}

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

 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:{...}
]

获取后我的状态是相同的方式。

更新我发现问题是:当状态改变时,组件没有用正确的道具重新渲染孩子。我在传递 props 的高阶组件中调用 API,并添加了一个 componentWillUpdate 方法来强制刷新组件的状态。不是理想的解决方案,但直到现在我才想出其他方法。有什么建议吗?

标签: javascriptreactjs

解决方案


我知道你的 api 响应是什么,但我用假 API 测试了你的代码并改变了

fetchApiToEntries(apiToFetch){}

转箭头功能(箭头功能

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

希望它可以帮助你。


推荐阅读