【问题标题】:Reload render issue after change props using Redux?使用 Redux 更改道具后重新加载渲染问题?
【发布时间】:2018-10-08 22:11:58
【问题描述】:

我在我的应用程序中使用 redux。只有一种状态被定义。我可以更改状态并渲染屏幕。但是每当我更改状态道具时,我都无法重新加载屏幕。

代码:

action-types.js

export const SET_NOTIFICATION = "SET_NOTIFICATION";

action.js

import {
    SET_NOTIFICATION,
} from "./action-types";

let initialState = {
    notyIndex: 0,
};

export const setNotyIndex = (notyIndex) => ({type: SET_NOTIFICATION, notyIndex});

reducer.js

import {
    SET_NOTIFICATION,
} from "./action-types";

let initialState = {
    notyIndex: 0,
};

export default reducer = (state = initialState, action) => {
    switch (action.type) {
        case SET_NOTIFICATION:
            return Object.assign({}, state, {notyIndex: action.notyIndex});
            break;
        default:
            return initialState;
            break;
    }
};

我连接 redux 如下。 DashBoard.js

import { setNotyIndex } from "./action";
import {connect} from "react-redux"

********* 生命周期开始 ************

 componentWillMount(){
  console.log('Call update');
  console.log('Index is',this.props.notyIndex);
 }

 shouldComponentUpdate=()=>{
    return true
  }
 componentDidUpdate=(prevProps, prevState, snapshot)=>{
    console.log('Call update');
    console.log('Index is',this.props.notyIndex);
  }

 componentDidMount() {
     console.log('Call update');
     console.log('Index is',this.props.notyIndex);
  }

*********生命周期结束************

const mapDispatchToProps = (dispatch) => {
  return {
      setNotyIndex: (notyIndex) => dispatch(setNotyIndex(notyIndex)),
  }
};

const mapStateToProps = (state) => {
    if (state === undefined) {
        return {};
    }
    return {
        notyIndex: state.notyIndex,
    }
};


connect(mapStateToProps, mapDispatchToProps)(DashBoard);

值设置为。

setNotyIndex(1);

- 如上代码设置值后没有调用生命周期方法。

谢谢。

【问题讨论】:

  • 请添加您的组件代码
  • @MotiKorets 实际上我已经在我的代码中添加了生命周期的所有方法,没有一个方法被调用。
  • 他的意思是你调用setNotyIndex的组件。 setNotyIndex action 或 SET_NOTIFICATION reducer 是否被调用?
  • @MotiKorets 你可以看到我的代码中使用的生命周期方法。
  • @riwu 我在按钮事件中调用了 setNotyIndex。

标签: reactjs react-native redux react-redux


【解决方案1】:

首先当你使用redux的方法时你必须用

this.props.setNotyIndex(1);

当你在组件中使用 redux 的 veriable 时,你必须使用

this.props.notyIndex

您可以在您的 ma​​pStateToProps 方法中进行控制台以获取类似以下的更改

const mapStateToProps = (state) => {
console.log("State veriable : ", state)
if (state === undefined) {
    return {};
}
return {
    notyIndex: state.notyIndex,
}

};

当您更改您的 redux 验证并且您在代码中使用该验证时,相关组件会重新渲染它。但是如果有一些问题,那么你可以在 redux 方法调用之后通过菜单调用 setState,比如在

this.props.setNotyIndex(1);
this.setState({

});

我希望它对你有用.......

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-30
    • 2020-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-26
    • 1970-01-01
    • 2021-07-13
    相关资源
    最近更新 更多