繁体   English   中英

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

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

我有一个返回json的函数:

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

我在这里得到通话结果:

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)返回我: {id:1,作者:{…},标题:“第一篇测试文章”,描述:“ sadasdsads”,img_name:“ D.png”,…}

但是我不能像使用asd一样在函数外部以状态形式写入此结果。

如果您能帮助我,我将不胜感激,也许有某种方式可以将this.props.articleDetail()的结果写入状态。

我还想问一下我是否可以将调用此函数的结果写入变量,然后该函数返回promise

另外,是否可以在此函数上设置一些变量并记录console.log返回到我的外部变量的内容。

非常感谢您的参与。

您如何检查状态是否改变?
为了正确检查状态是否已更新,请像这样对setState函数应用回调(请记住setState是异步的):

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

关于您关于在生命周期方法中设置状态的评论,那么只要您在componentWillMount而不是componentDidMount

暂无
暂无

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

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