繁体   English   中英

React componentDidMount获取api

[英]React componentDidMount fetch 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));
}

我无法理解生命周期中缺少的东西。 不应做出以下反应吗?

  • 初始状态
  • 给予
  • 调用componentDidMount
  • 重新呈现

这是我的初始组件:

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

获取后我的状态是一样的。

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

你需要在构造函数中绑定fetchApiToEntries还是使用胖箭头?

this.fetchApiToEntries = this.fetchApiToEntries.bind(this);

对不起,我不能评论不够的代表

请问您的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.
            )
        }
    }

希望它能帮到你。

暂无
暂无

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

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