Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript React componentDidMount获取api_Javascript_Reactjs - Fatal编程技术网

Javascript React componentDidMount获取api

Javascript React componentDidMount获取api,javascript,reactjs,Javascript,Reactjs,我正在尝试获取componentDidMount中的api。api结果将被设置为组件的状态,状态映射并传递给子组件 如果我在内部使用获取方法获取api,那么componentDidMount一切正常: componentDidMount(){ fetch(apiToFetch) .then((result) => result.json()) .then((result) => result.entries) .then((en

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

如果我在内部使用获取方法获取api,那么componentDidMount一切正常:

componentDidMount(){
    fetch(apiToFetch)
        .then((result) => result.json())
        .then((result) => result.entries)
        .then((entries) => this.setState({ ...this.state, entries }))
        .catch((error) => console.log(error));
}
如果在方法内使用获取,然后在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>
        )
    }
}
这是控制台中实际条目的外观:

 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,该组件传递了props,并添加了一个componentWillUpdate方法,该方法强制执行状态刷新,从而重新启动该组件。这不是理想的解决方案,但我现在还没有找到其他办法。有什么建议吗?

您需要在构造函数中绑定fetchApiToEntries还是使用fat箭头

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

很抱歉,我无法评论不够的rep

Idk您的api响应是什么,但我用一个假的api测试了您的代码并更改了它

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


希望对您有所帮助。

我知道构造函数中缺少方法绑定。您不应该执行以下操作吗?-应该这样。如果我在一个方法中使用fetch,然后在componentDidMount中调用这个方法,则不会呈现任何内容—这是不可能的。只要
apiToFetch
相同,这两个
componentDidMount
片段的行为应该完全相同。考虑提供一种复制问题的方法。它应该工作,请检查控制台日志是否有任何错误,或者在CODEPTEN上复制这个版本,这样就可以很容易地为其他人调试发布日志了,并向我们展示<代码>结果的结构。条目< /代码>?您在控制台、网络或浏览器中是否出现错误?我没有收到错误,我必须编辑我的问题:两种方法给出相同的结果。我想我在最初的状态中缺少了一些东西。我会更新这个问题。不,你不需要。正如我在评论中所说的,我知道它丢失了,但在这种情况下它是不相关的…打断它设置状态的位并检查其中的内容。因为它的绑定在fetch和setState之后一直向下(使用胖箭头),所以会触发重新渲染。我猜这不是你想要的。这段代码没有箭头是可行的,所以这里不需要。谢谢,但我以前也尝试过,没有任何变化,我已经在问题编辑中发布了api响应。顺便说一下,在一个简单的
  • 中映射状态,而不是在子组件中映射状态,效果很好。我想知道我是否必须在高阶组件中设置状态,并将状态作为道具传递,即使我觉得这是不必要的。
    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.
                )
            }
        }