【问题标题】:State is updating to the component but props is undefined状态正在更新到组件,但道具未定义
【发布时间】:2018-11-30 16:51:20
【问题描述】:

我只是尝试将 redux 集成到我的 react-native 应用程序中。CombineReducer 用于组合两个减速器,但它给了我未定义的道具。

计数器组件

 function mapStateToProps(state) {
   console.log(props)  //undefined
   console.log(state); // counterReducer: { counter: 2 }
   return {
       counter: state.counter
   };
  }

reducerIndex.js

import { combineReducers } from 'redux';
import { todoReducer } from './todoReducer';
import { counterReducer } from './counterReducer';
export default combineReducers({
  counterReducer,
  todoReducer
});

App.js

const store = createStore(reducer);

export default class App extends Component {
  render() {
     return (
      <Provider store={store}>
       <CounterApp />
      </Provider>
   );
  } 
}

【问题讨论】:

  • 是的,它应该给你 undefined 因为 mapStateToProps 内部不知道 props 是什么意思。只有状态在函数内部传递。你仍然可以在你的类中使用 props 并获取 redux 存储值。

标签: javascript react-native redux react-redux


【解决方案1】:

是的,对于在mapStateToProps 中访问的道具来说,这是一个有效的undefined,因为mapStateToProps 只是一个普通函数,它将redux 状态暴露给您使用connect 附加到商店的组件。 mapStateToProps 不知道您的组件 props,但 它确实会更新它们或通过将您的 redux 状态作为 props 提供给组件来添加更多内容,这就是为什么将函数名称写为mapStateToProps! 所以当你写以下内容时:

class MyContainer extends Component {
   constructor (props) {
      super (props);
   }
   ......
   .....
   render () {
    return <MyCoolComponent />
   }
};

function mapStateToProps(state) {
  const {myreducer} = state;
  return {
     data: myreducer.data 
  }
}

function mapDispatchToProps (dispatch, ownProps) {
   return {
      updateData: () => {
         dispatch(someAction());  //someAction: this will return something like this: {type: MY_UPDATE_ACTION}
      }
   }
}

export default connect(mapStateToProps, mapDispatchToProps)(MyContainer);

所以在MyContainer 组件中,您将可以访问data 作为其道具之一。您可以使用this.props.data 访问课堂中任何地方的数据。

另一方面,mapDispatchToProps 将函数作为 props 暴露给附加的组件,被暴露的函数可以访问 dispatch,它实际上向 store 分派一个动作,从而使您的组件能够改变 redux 存储。所以通过上面的解释,updateData 函数可以从MyContainer 中的任何地方使用this.props.updateData() 访问。

【讨论】:

    猜你喜欢
    • 2020-01-16
    • 1970-01-01
    • 2020-07-30
    • 2016-09-19
    • 2021-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-22
    相关资源
    最近更新 更多