กำลังเปลี่ยนสถานะ / อุปกรณ์ประกอบฉากขององค์ประกอบรูทด้วย Redux หรือไม่

ฉันมีองค์ประกอบรูทที่แสดงผลดังนี้:

<Provider store={store}>
  <IntlProvider locale="en" messages={this.state.messages}>
    <Router>
      <App>
        // routes
      </App>
    </Router>
  </IntlProvider>
</Provider>

ฉันได้รับ this.state.messages แบบไดนามิก (async, Redux action + ตัวลด) จากส่วนหลังเป็นวัตถุ ฉันเก็บไว้ในร้าน Redux ฉันจะส่ง Redux store messages ถึง this.state.messages ได้อย่างไร (props ก็ทำได้เช่นกัน)

พล็อตเรื่องบิดเบี้ยว: ฉันไม่สามารถใช้ react-redux connect กับส่วนประกอบนี้ได้ เพราะมันเป็นองค์ประกอบรูทและไม่ได้อยู่ใน <Provider> (แนะนำมัน) ดังนั้นให้ทำสิ่งนี้:

const mapStateToProps = state => {
  return {
    messages: state.messages
  }
}

export default connect(mapStateToProps)(RootComponent);

สิ้นสุดใน:

Uncaught Error: Could not find "store" in either the context or props of "Connect(RootComponent)". Either wrap the root component in a <Provider>, or explicitly pass "store" as a prop to "Connect(RootComponent)".

มีวิธีการเข้าถึงร้าน Redux ในลักษณะที่แตกต่างและมีเหตุผลหรือไม่? ฉันกำลังคิดถึง store.getState() แต่มันไม่ยอมรับข้อโต้แย้งและการแมปกับรายการสถานะทั้งหมดดูเหมือนจะเกินความจำเป็นเมื่อฉันต้องการได้เพียงหนึ่งรายการ หรือบางทีฉันอาจทำอะไรผิดและท้ายที่สุด connect ควรทำงานที่นี่


person Wordpressor    schedule 26.11.2017    source แหล่งที่มา


คำตอบ (1)


คุณสามารถสร้างส่วนประกอบการตอบสนองที่เชื่อมต่อซึ่งจะล้อม IntlProvider และส่งข้อความไปยังส่วนประกอบดังกล่าว

โค้ดตัวอย่าง (ยังไม่ได้ทดสอบ):

const ConnectedIntlProvider = ({ children, ...props }) => ( // the props contain the messages and the locale
  <IntlProvider locale="en" { ...props }>
  { children }
  </IntlProvider>
);

const mapStateToProps = state => ({
  messages: state.messages
});

export default connect(mapStateToProps)(ConnectedIntlProvider);

ประเพณี:

<Provider store={store}>
  <ConnectedIntlProvider locale="en">
    <Router>
      <App>
        // routes
      </App>
    </Router>
  </ConnectedIntlProvider>
</Provider>
person Ori Drori    schedule 26.11.2017