繁体   English   中英

Redux无法分配整数值

[英]Redux fails assigning integer value

在CategoryFeed类中,我有以下内容:

class CategoryFeed extends Component {
...
componentDidMount() {
const {
      params,
      currentForum,
      updateCurrentForum,
    } = this.props;

    alert(params.fid);
    updateCurrentForum(params.fid);
    alert(currentForum);
}
...
export default connect(
  (state) => { return {
    currentForum: state.app.currentForum,
...
(dispatch) => { return {
    updateCurrentForum: (currentForum) => { dispatch(updateCurrentForum(currentForum)); },
...

这是updateCurrentForum的样子:

export const updateCurrentForum = (currentForum) => {
  alert("inside is " + currentForum);
  return {
    type: UPDATECURRENTFORUM,
    payload: currentForum,
  };
};

在Reducer中,我定义为:

case UPDATECURRENTFORUM:
      return Object.assign({}, state, {
        currentForum: action.payload,
      });

这是我期望的工作方式。

  1. 加载CategoryFeed时,它会警告params.fid(假设params.fid = 1)。 params.fid实际上是主URL之后的附加字符串(例如,如果url为http:// localhost / 1 ,则params.fid为1)。
  2. 然后通过Redux将params.fid(= 1)的值存储到currentForum
  3. 通过将有效负载值设置为currentForum之后,然后尝试在componentDidMount()中提醒currentForum的值。 但是,它不会显示“ 1”,但是会显示“ undefined”。 似乎redux无法将params.fid放入currentForum。

我怎样才能解决这个问题?

您将无法在componentDidMount()获取currentForum的更新值。 这是因为componentDidMount()仅在组件安装后运行。

componentDidMount() prop的更改将导致组件重新呈现。 因此,可以在render()componentDidUpdate()周期中访问更新的值。

您可以将alertconsole.log移至render方法,并且应该看到更新后的值

componentDidMount组件插入到DOM树之后将被调用,里面是你叫updateCurrentForum(params.fid)将更新currentForum但这种变化将在被抓componentDidUpdate 有关更多详细信息,请参见组件http://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/

目前currentForum持有

const {
  params,
  currentForum,
  updateCurrentForum,
} = this.props;

当前可能未定义。 尝试在道具中分配一些值,看看它是否从未undefined变为您提供的value

暂无
暂无

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

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