简体   繁体   English

在同一组件中两次设置状态

[英]set state twice in the same component

I am trying to setState to an event category for display inside of handleCategoryChange . 我正在尝试将setState设置为事件类别,以便在handleCategoryChange内部显示。 The categories are rendered from the getCategories fetch point. 类别是从getCategories提取点呈现的。 I need to send a different value to the action fetch call in createEventHandler . 我需要向createEventHandler的操作访createEventHandler调用发送一个不同的值。 The set state only happens once though and omits the second to send the first value of the state . 设置状态仅发生一次,并且省略第二个以发送状态的第一个值 Is there a work-around for this? 是否有解决方法? or is this a limitation of react? 还是这是反应的局限性?

//... styles and imports

class NewEvent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      event: {
        category: ''
      }
    };
    this.createEventHandler = this.createEventHandler.bind(this);
    this.handleCategoryChange = this.handleCategoryChange.bind(this);
  }
  handleCategoryChange(evnt) {
    this.setState({
      event: {
        ...this.state.event,
        category: evnt.target.value
      }
    });
  }
  componentWillMount() {
    this.props.getCategories();
  }
  renderStepOne() {
    const { event } = this.state;
    const { categories } = this.props;
    return (
      <div style={styles.flexColumn}>
        <Typography variant="title">Event</Typography>
        <Select
          value={event.category}
          onChange={this.handleCategoryChange}
          error={categoryError.length > 0}
        >
          {categories.map(category => (
            <MenuItem key={category.id} value={category.name}>
              {category.name}
            </MenuItem>
          ))}
        </Select>
      </div>
    );
  }
  createEventHandler() {
    const { event } = this.state;

    if (!error) {
      let categoryId = this.props.categories.filter(e => {
        if (e.name === event.category) {
          return e;
        }
      });
      categoryId = categoryId[0].id;

      this.setState({
        event: {
          ...event,
          category: categoryId
        }
      });
      this.props.createEvent(event, this.props.history);
    }
  }
  render() {
    const { step } = this.state;
    const { isFetching, user, categories } = this.props;
    return (
      <ViewContainer title="New Event" isFetching={isFetching}>
        <Paper style={styles.paper}>
          <div style={styles.body}>{this.renderStepOne()}</div>
          <MobileStepper
            type="dots"
            steps={0}
            position="static"
            nextButton={
              <Button
                variant="raised"
                color="primary"
                onClick={this.createEventHandler}
                disabled={isFetching}
              >
                Submit
                <KeyboardArrowRight />
              </Button>
            }
          />
        </Paper>
      </ViewContainer>
    );
  }
}
const mapStateToProps = state => ({
  categories: state.events.categories
});
const mapDispatchToProps = dispatch => ({
  createEvent: (event, history) => dispatch(createEvent(event, history)),
  getCategories: () => dispatch(getCategories())
});
export default connect(
  mapStateToProps,
  mapDispatchToProps
)(withRouter(NewEvent));

You could try using functional setState like so: 您可以尝试使用功能性setState,如下所示:

this.setState(() => ({
  event: {
    ...this.state.event,
    category: evnt.target.value
  })
});

So that everything involving a setting of state happens together. 这样,涉及状态设置的所有事物都会同时发生。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM