React-Redux mapStateToProps不是到处都被调用

时间:2019-02-03 05:54:02

标签: reactjs react-native react-redux redux-thunk

我正在处理React内部的Flash消息

const mapStateToProps = state => {
  console.log(state.flashMessages);             <---This
  return {
    messages: state.flashMessages
  };
};
export class FlashMessagesComponent extends Component {
   render(){
     return <h1>Flash</h1>
   }
}
export default connect(mapStateToProps)(FlashMessagesComponent);

将FlashMessagesComponent视为在People中调用的Flash消息传递组件

http://localhost:3000/people              <--works here

import React from 'react';
const People = () =>{
    return (
        <div>
            <FlashMessagesComponent/>
            <h1>People Page</h1>
        </div>
    )
}

export default PeopleDashboard ;
  

尖点记录flashMessages的状态

但是

http://localhost:3000/basic          <--not here

const BasicPage = () =>{
    return (
        <div>
            <FlashMessagesComponent/>
            <h1>Basic Page</h1>
        </div>
    )
}

export default  BasicPage;
  

尖线不记录,即mapStateToProp不起作用

1 个答案:

答案 0 :(得分:1)

原因是您导出FlashMessageComponent而不是connected FlashMessageComponent

更改

export class FlashMessagesComponent extends Component {
   render(){
     return <h1>Flash</h1>
   }
}
connect(mapStateToProps)(FlashMessagesComponent);

class FlashMessagesComponent extends Component {
   render(){
     return <h1>Flash</h1>
   }
}
export default connect(mapStateToProps)(FlashMessagesComponent);