下面是我的组件,我试图从状态中获取属性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开发工具中看到状态更改后的值。
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;
答案 0 :(得分: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
}
});