简体   繁体   English

如何保存到状态并保存到获取API的本地变量结果

[英]how save to state and save to local variable result from fetch api

I have a function that returns json: 我有一个返回json的函数:

const mapDispatchToProps = dispatch => {
  return {
    articleDetail: (id) => {
        return dispatch(articles.articleDetail(id));
    }
  }
};

I get the result of the call here: 我在这里得到通话结果:

class ArticleDetail extends Component {

constructor(props) {
    super(props);
    this.state = {
        articleId: props.match.params.id,
        asd: "",
        art:{}
    };
}

componentWillMount() {
    this.props.articleDetail(this.state.articleId).then((res) => {
        console.log(res.article);
        this.setState({art:res.article})
    });
    this.setState({asd: "asda"})
}

console.log(res.article) return me: {id: 1, author: {…}, headline: "First test article", description: "sadasdsads", img_name: "D.png", …} console.log(res.article)返回我: {id:1,作者:{…},标题:“第一篇测试文章”,描述:“ sadasdsads”,img_name:“ D.png”,…}

but I can't write this result in state, just outside the function, as I did with asd. 但是我不能像使用asd一样在函数外部以状态形式写入此结果。

I would appreciate it if you would help me, maybe there is some way to write the result of this.props.articleDetail () in state. 如果您能帮助我,我将不胜感激,也许有某种方式可以将this.props.articleDetail()的结果写入状态。

I also wanted to ask if I could write the result of calling this function into a variable, and the function returns promise 我还想问一下我是否可以将调用此函数的结果写入变量,然后该函数返回promise

And also, is it possible to set some variable over this function and record what my console.log "returns" to my external variable. 另外,是否可以在此函数上设置一些变量并记录console.log返回到我的外部变量的内容。

Thank you so much for your time. 非常感谢您的参与。

how did you check if the state changed? 您如何检查状态是否改变?
In order to properly check if the state has been updated apply a callback to the setState function like this (remember that setState is async): 为了正确检查状态是否已更新,请像这样对setState函数应用回调(请记住setState是异步的):

this.setState({ art: res.article }, () => {
    // this happens after the state has been updated
    console.log(this.state.art);
});

in regards to your comment about setting the state in the lifecycle methid then it's perfectly fine as long as you do it in componentWillMount and not in componentDidMount . 关于您关于在生命周期方法中设置状态的评论,那么只要您在componentWillMount而不是componentDidMount

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

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