React / Redux传递状态更改<picker>

时间:2018-07-25 12:16:14

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

我正在使用react-native Picker组件,并且在值更改时无法更新全局状态。

我以前从未使用过Redux,并且阅读过Redux是将状态传递给非父/子组件的唯一解决方案之一。我有一个处理API的Network.js文件。当用户选择一个值来更新状态时,我想将状态传递给Network.js。

这是我的App组件和PageOne组件的代码 App.js。非常感谢

const initialState = {
  count: 0
};

const reducer = (state = initialState, action) => {
  if(action.type === "REGIONAL_ID") {
    return {
      regionId: state.regionId
    };
  }
  return state;
}

const store = createStore(reducer);

export default class App extends React.Component {
  render(){
    return (
      <Provider store={store}>
        <BottomTabNav />
      </Provider>
    )
  }  
}

PageOne.js

class PageOne extends Component {
  constructor(props) {
    super(props);
  }
  
  changeRegion = (regId) => {
    // How to add/dispatch the regId to the prop 
    this.props.dispatch({ type: 'REGIONAL_ID' });
  }

  render() {
    return (
    <View >
      <Picker
	selectedValue={this.state.regionId}
	style={{ flex:1, height: 50, width: SCREEN_WIDTH }}
	onValueChange={itemValue => this.changeRegion(itemValue)}>
	<Picker.Item label="One" value='1' />
	<Picker.Item label="Two" value='2' />
      </Picker>
    </View>
    )
  }
}

const mapStateToProps = state => ({
  regionId: state.regionId
})
export default connect(mapStateToProps)(PageOne)

1 个答案:

答案 0 :(得分:2)

在App.js中,您应该返回 new 状态:

const reducer = (state = initialState, action) => {

  if(action.type === "REGIONAL_ID") {
     return {
        regionId: action.regionId
      };
    }
    return state;
}

在PageOne.js中,只需执行以下操作:

changeRegion = (regId) => {
  // How to add/dispatch the regId to the prop 
  this.props.dispatch({ type: 'REGIONAL_ID', regionId: regId });
}

这将更新状态中的regionId。