React Native / Redux:每次状态更改时如何将更新后的状态传递给子组件?

时间:2016-09-01 19:32:06

标签: javascript reactjs react-native redux react-jsx

在React Native和Redux中,我使用<location inheritInChildApplications="false"> <context type="SomeApp.Models.DataContext, SomeApp"> <databaseInitializer type="..."> <parameters> <parameter value="SomeConnection_DatabasePublish" /> </parameters> </databaseInitializer> </context> </location> 作为根组件并使用<NavigationCardStack/>呈现路由。但似乎只要根组件重新呈现状态更新,它就不会在每次更新时都将状态向下传递,因为我将_renderScene()放在子组件中并记录传递状态,但它只记录一次,那就是应用程序第一次启动时,即使根组件使用状态更新重新呈现,也不会记录。

为什么每次状态发生变化时都不会传递更新后的状态?为什么每个根组件都不会重新呈现子组件?

这是我的设置:

console.log(this.props)

_renderScene (props) { const { route } = props.scene return ( <route.component _handleNavigate={this._handleNavigate.bind(this)} state={this.props}/> ) } <NavigationCardStack direction='horizontal' navigationState={this.props.navigation} onNavigate={this._handleNavigate.bind(this)} renderScene={this._renderScene} renderOverlay={this.renderOverlay} style={styles.container} /> _renderScene单独记录:

enter image description here

props记录通过Redux传递的实际状态:

enter image description here

在子组件this.props中,我只是这样记录,并且正确记录传递的道具(childPage.js_handleNavigate),但state只是即使它得到更新,它仍然代表初始状态:

state

提前谢谢!

修改

这是我的reducer,子组件只会在这里记录initialState,即使已经添加和更新了其他属性:

  render() {
    console.log(this.props.state)

    return (

并连接到根组件,如下所示:

const initialState = {
  meetUp: false,
}

function itemReducer(state = initialState, action) {
  switch(action.type) {


    case ITEM_QUANTITY:
      return {
        ...state,
        quantity: action.quantity
      }

    case ITEM_PRICE:
      return {
        ...state,
        price: action.price
      }

    case ITEM_MEET_UP:
      return {
        ...state,
        meetUp: action.meetUp
      }

     default:
       return state
  }
}

export default itemReducer

采取以下行动:

function mapStateToProps(state) {
  return {
    itemInfo: state.itemReducer,
    ...
  }
}

export default connect(
  mapStateToProps,
  {
    itemQuantity: (value) => itemQuantity(value),
    itemPrice: (value) => itemPrice(value),
    itemMeetUp: (value) => itemMeetUp(value),
  }
)(NavigationRoot)

2 个答案:

答案 0 :(得分:1)

只有一个原因是子组件在父渲染后不呈现 - 它的shouldComponentUpdate方法,或者它与父组件之间的组件中的组件返回false。通常(特别是使用Redux)如果属性没有被浅浅地,则编写shouldComponentUpdate方法来阻止重新呈现。 Redux依赖于你不改变状态,而是总是从reducer返回一个新对象,否则shouldComponentUpdate优化会导致意外行为。

问题是您是在修改深度状态而不是返回新对象吗?有关详细信息,请参阅http://redux.js.org/docs/basics/Reducers.html

答案 1 :(得分:0)

第一个猜测是你的NavigationCardStack没有重新渲染,因为它认为呈现给它的道具没有变化。尝试强制重新呈现(forceUpdate)并查看会发生什么。