【问题标题】:how save to state and save to local variable result from fetch api如何从 fetch api 保存到状态并保存到局部变量结果
【发布时间】:2018-10-21 05:26:20
【问题描述】:

我有一个返回 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 “返回”到我的外部变量。

非常感谢您的宝贵时间。

【问题讨论】:

  • but I can't write this result in state, just outside the function, as I did with asd. 你遇到错误了吗?
  • 不,我只是没有得到状态的变化。我只对我列出的可能使用语法 javascript 的这 3 个操作感兴趣
  • 如何检查状态是否改变?是否附加了一些 ui 元素?另外,您可以尝试将状态更改更改为this.setState({ art: res.article }, () => { console.log(this.state.art); });,以便查看它是否更改
  • 哦,谢谢,其实是的,状态正在更新,显然我写的console.log不在那里,我需要重新读取序列是如何加载组件的
  • 我理解正确,所以我可以将api响应中的数据写入到上面声明的这个生命周期函数中的变量中?

标签: javascript json reactjs


【解决方案1】:

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

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

关于您关于在生命周期方法中设置状态的评论,那么只要您在 componentWillMount 中而不是在 componentDidMount 中执行它就可以了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-15
    • 2021-08-22
    • 1970-01-01
    • 2014-05-25
    • 2020-03-14
    • 1970-01-01
    相关资源
    最近更新 更多