如何从商店获取状态并传递给新组件?

时间:2017-07-07 07:21:04

标签: react-native redux react-redux

好吧我对React-native和redux相当新,所以请保持简单。我做了一些研究并阅读了redux docs的可能,但也许我不是在寻找正确的信息。

首先我创建一个计划。

class PlanCreate extends Component {
   onButtonPress() {
       const {title, city, district} = this.props;

       this.props.planCreate({title, city, district});
   }
    render () {
      return (
        <View>
          <CardSection>
            <Input
              lable="Title"
              placeholder="New Plan"
              autoCorrect={false}
              value={this.props.title}
              onChangeText={value => this.props.planUpdate({prop: 'title', value})}
            />
          </CardSection>
          <CardSection>
            <Input
              lable="City"
              placeholder="Oakland"
              autoCorrect={true}
              value={this.props.city}
              onChangeText={value => this.props.planUpdate({prop: 'city', value})}
            />
          </CardSection>
           <CardSection>
            <Input
              lable="District"
              placeholder="Chinatown"
              autoCorrect={true}
              value={this.props.district}
              onChangeText={value => this.props.planUpdate({prop: 'district', value})}
            />
          </CardSection>

          <CardSection>
            <Button onPress={this.onButtonPress.bind(this)}>
              Create Plan
            </Button>
          </CardSection>
        </View>
      );
    }
  }
  const styles = {
    pickerTextStyle: {
      fontSize: 18,
      paddingLeft: 20
    }
  };
  const mapStateToProps = (state) => {
    const {title, city, district} = state.planForm;
    return {title, city, district}
  };
  export default  connect(mapStateToProps, {planUpdate, planCreate})(PlanCreate);

然后将其发送到我的rails后端服务器

export const planCreate = ({ title, city, district}) => {
    return (dispatch) => {
      var user_id = 1;
       axios.post('http://localhost:3000/plans', { params: { user_id: user_id, title: title, city: city, district: district}
      }).then((response) => {
        dispatch({ type: PLAN_CREATE, payload: response.data});
       Actions.plan();
      });
    };

然后我用新的plan_id从服务器更新我的状态。

export default (state = INITIAL_STATE, action) => {

switch (action.type) {
  case PLAN_UPDATE:
    return { ...state, [action.payload.prop]: action.payload.value};
  case PLAN_CREATE:
    return { ...state, plan_id:  action.payload.id};
  default:
    return state;
  }
};

在此之后我导航到一个新页面,从那里我需要从状态中获取新分配的plan_id,并从新页面向我的服务器发送新的帖子请求中引用它。

0 个答案:

没有答案