【问题标题】:Why does my action cause the props to change?为什么我的动作会导致道具发生变化?
【发布时间】:2019-10-29 01:09:03
【问题描述】:

我有一个显示收到的帖子的组件和另一个显示用户发布的帖子的组件,我的操作会根据他们单击的选项卡来抓取帖子。下面是动作。

import {  FETCH_POSTS_RECEIVED  } from './types';



export const fetchPostReceived = (id) => dispatch => {
    fetch('/posts/vh5given/' + id , {
        method: 'GET',
        headers: {
            'content-type' : 'application/json'
        }
    })
    .then(res => res.json())
    .then(userPosts => dispatch ({
        type:FETCH_POSTS_RECEIVED,
        payload: userPosts
    }));
    // .then(data = console.log(data));
  }

export const fetchPostsFromUser = (id) => dispatch => {
  fetch('/posts/' + id , {
      method: 'GET',
      headers: {
          'content-type' : 'application/json'
      }
  })
  .then(res => res.json())
  .then(posts => dispatch ({
      type:FETCH_POSTS_FROM_USER,
      payload: posts
  }));
  // .then(data = console.log(data));
}

它们的函数在 ComponentDidUpdate 上调用

componentDidUpdate(prevProps) {
    // console.log(prevUserId);
    let prevUserId = prevProps.user.map((user) => (user.id));
    let userId = this.props.user.map((user) => (user.id));
    if(prevUserId.length < 1 || prevUserId == undefined && userId) {
      console.log("Currently Updating from vh5");
      console.log(prevUserId);
      console.log(userId);
    this.props.fetchPostReceived(userId);
    }
  }

componentDidUpdate(prevProps) {
  // console.log(prevUserId);
  let prevUserId = prevProps.user.map((user) => (user.id));
  let userId = this.props.user.map((user) => (user.id));

  if(prevUserId.length < 1 || prevUserId == undefined){console.log('undefineeeeed')}
  if(prevUserId.length < 1 || prevUserId == undefined && userId) {
    console.log("Currently Updating");
    console.log(prevUserId);
    console.log(userId);
    this.props.fetchPostsFromUser(userId);

    console.log('this is the props ' + this.props.posts)
  }
}

我遇到的问题是,当调用 Fetch Post Received 函数时,道具会发生变化。因为我在更新时从道具状态渲染帖子,所以显示了错误的帖子。

为什么会发生这种情况,我该如何解决?

【问题讨论】:

  • 为什么会有2个componentDidUpdate?
  • 如果我对您的理解正确,问题很可能出在减速器中(如果状态正在发生您不期望的更改)。你能展示一下减速机吗?
  • 对不起,如果我不清楚,但它是两个不同的组件
  • 哇,谢谢詹姆斯,我在另一个减速器中有 FETCH_POST_RECEIVED,所以它出现了两次。谢谢!
  • 我认为减速器可能有问题。可能是你没有以不可变的模式改变你的对象。但也有一个困惑,你提到道具改变了。你这么说到底是什么意思?

标签: reactjs redux


【解决方案1】:

我无法添加评论,但是您是两次调用 componentDidMount(这是您的代码所建议的),还是您尝试过的那两个单独的事情,因为

  let prevUserId = prevProps.user.map((user) => (user.id));
  let userId = this.props.user.map((user) => (user.id));

    this.props.fetchPostsFromUser(userId);

两次射击可能是您的问题。

【讨论】:

    猜你喜欢
    • 2010-09-30
    • 1970-01-01
    • 1970-01-01
    • 2011-01-09
    • 2015-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多