【问题标题】:React component not able to get updated state valueReact 组件无法获取更新的状态值
【发布时间】:2019-10-18 05:03:38
【问题描述】:

下面是我的组件,我正在尝试从状态中获取属性text 的更新值。但我无法获得更新的值,我只看到默认值:

 class MainPage  extends Component {
  render () {
    const { classes } = this.props;
    return (
      <div className="MainStyle">
      <Grid container spacing={3}>
      <Grid item xs={8}>
          <Paper className={classes.paper}>
              <AdvancedEars />
          </Paper>
        </Grid>
        <Grid item xs={4}>
          <Paper className={classes.paper}>
              <Clicker />
          </Paper>
        </Grid>
        <Grid item xs={12}>
          <Paper className={classes.whiteboard}>
           S: { this.state.text }
          </Paper>
        </Grid>
      </Grid>
    </div>
    );
  }
}

MainPage.propTypes = {
  classes: PropTypes.object.isRequired,
  text: PropTypes.string.isRequired,
};

const mapStateToProps = state => (()=>
{
  console.log('I AM HERE');
  console.log(state);
  return {
    text: state.text
  }
});

export default compose(
  withStyles(styles),
  connect(mapStateToProps)
)(MainPage);

下面是改变状态的组件。我可以在 redux 开发工具中看到 state 中的值发生了变化。

class Clicker  extends Component {
  render () {
    return (
      <Grid item xs={4}>
      <Button 
      variant="contained"
      color="primary"
      size="large"
      onClick={ this.props.saveData( "THIS IS ME" ) } >
          <Mic fontSize="large" />
      </Button>
  </Grid> 
    );
  }
}

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


const mapDispatchToProps = dispatch => ({
  saveData: text => dispatch(saveText( { text } ))
});

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Clicker);

单击按钮时,我应该能够看到值为THIS IS ME,但我无法获取该值,它一直是空白的。这是减速器:

const defaultState = {
  text: ""
};

const transcribeReducer = (state = defaultState, action) => {
  switch (action.type) {
    case ActionTypes.TEXT_SAVE: {

      let { text } = action.payload;
      let newState = {
          ...state,
          text,
      }
      return newState;
    }

    default:
      return state;
  }
};

export default transcribeReducer;

【问题讨论】:

    标签: reactjs react-redux


    【解决方案1】:

    mapStateToProps 需要是一个将 redux 状态映射到传递给组件的 props 的函数。

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

    在您的代码中,mapStateToProps 是一个返回另一个返回状态的函数的函数:

    const mapStateToProps = state => (()=>
    {
      console.log('I AM HERE');
      console.log(state);
      return {
        text: state.text
      }
    });
    

    【讨论】:

    • 另外,在MainPage里面,你访问的是this.state.text,我猜你要找的是this.props.text
    • 是的 this.props.text ,但我仍然无法访问状态值。在我有控制台输出I AM HERE 的函数中,我可以使用属性text 设置状态,但它是空的。
    • 你的mapStateToProps也错了,你修了吗?
    • 我发现了问题。这是因为我在reducer中直接使用状态对象,当我克隆它然后使用它时它开始工作了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多