【问题标题】:Why is mapStateToProps not being called为什么不调用 mapStateToProps
【发布时间】:2018-01-31 02:42:30
【问题描述】:

我在用头撞墙。我已经用 React+Redux 顺利运行了一段时间,然后我使用 Chrome 删除了我的 localStorage,一切都变得混乱了。现在我无法调用 mapStateToProps ,所以即使减速器获得正确的状态,我也没有得到任何道具。

我已经阅读了 Redux 文档中关于 mapStateToProps 没有被调用的故障排除部分,但它似乎主要归结为不要改变你的状态。为了确保我不是,我已经将我的 reducer 代码减少到几乎没有以排除可能性。这里是:

const mapStateToProps = (state, ownProps) => {
    return {
      user: state.rootReducer.user
    }
}

export const rootReducer = (state = {}, action) => {
   switch (action.type) {
       case 'SET_CURRENT_USER':
           return Object.assign({}, state, {user: action.user});
           break;
       default:
           return state
    }
    return state
}

const store = createStore(
    reducer,
    applyMiddleware(middleware), 
    autoRehydrate()
)

const reducer = combineReducers({
  rootReducer: rootReducer,
  routing: routerReducer,}
)

使用@connect(mapStateToProps, mapDispatchToProps) 连接我的一个测试组件。过去我对此没有任何问题,我使用更标准的非装饰器实现对其进行了几次测试,但没有骰子。

任何想法都会非常有帮助。

这是精简的组件:

@connect(mapStateToProps, mapDispatchToProps)
export class TestComponent extends React.Component {
    constructor(props) {
        super(props);
        autobind(this);
    }

    componentDidMount() {
        store.dispatch(setCurrentUser({id:1}))
    }

    render() {
        return (
            <div>

            </div>
        )
    }
}
export class TestPage extends React.Component {
    constructor(props) {
        super(props);
        autobind(this);

        }

    render() {
       return (
           <div>
               <TestComponent />
           </div>
        )
    }


}

【问题讨论】:

  • 不应该这样。你调试检查了吗?
  • 两个建议 1) 添加一个 console.log('here')mapStateToProps仔细检查 它没有被调用(而不是产生破坏下游事物的输出) , 2) 在您的@connect 声明上方包含,以便我们可以在联系中看到它。
  • 我已经确认没有调用 mapStateToProps 的日志。
  • 我添加了一个精简的组件,它调用了 reducer,但 mapStateToProps 没有。
  • 已解决:我不知道我的生活出了什么问题...我只是将所有内容从我的 containers.jsx 文件复制到一个新文件 containers2.jsx 并更改了导入行,它正在工作.真的很奇怪。很想知道它是否可能与热加载器或其他东西有关。

标签: javascript reactjs react-redux


【解决方案1】:

试试这个:

const mapStateToProps = (state, ownProps) => {return {user: state.user}}

希望对你有帮助!

【讨论】:

  • uisng 箭头函数在这里什么都不做。
猜你喜欢
  • 2018-02-18
  • 2018-01-13
  • 1970-01-01
  • 1970-01-01
  • 2018-06-15
  • 2018-05-10
  • 2017-05-03
  • 2016-07-15
  • 2020-03-28
相关资源
最近更新 更多