【发布时间】:2018-05-21 14:03:32
【问题描述】:
由于我有一个带有表单的组件,我需要将表单连接到组件状态。初始数据来自 Redux,因此尝试通过使用 props 设置状态来初始化和更新组件:
componentWillMount = () => {
this.setState({
language: this.props.language || 'en'
})
}
language 是一个已连接的道具,我检查了它是否在商店中更新。
const mapStateToProps = state => ({
language: state.language
})
我也尝试使用componentWillReceiveProps 和componentWillUpdate,但它不起作用。我得到了初始状态,即使 store 和 connected props 发生了变化,组件的状态也不会更新。
{this.props.language} // updates
{this.state.language} // doesn't change
从 Redux 数据管理表单的正确方法是什么?
render 部分:
render () {
const {classes, theme, web} = this.props
const language = (
<CardContent>
<Typography type="headline">
Language
</Typography>
<Divider/>
<form className={classes.container} autoComplete="off">
<FormControl fullWidth margin="normal">
<InputLabel htmlFor="language">Select Block</InputLabel>
<Select
value={this.state.language} // <==================== language
onChange={this.handleLanguaheChange}
input={<Input id="language"/>}
>
<MenuItem value={'en'}>English</MenuItem>
<MenuItem value={'he'}>עברית</MenuItem>
</Select>
</FormControl>
</form>
</CardContent>
)
...
return (
<Grid
container
spacing={theme.spacing.unit * 3}
justify={'space-between'}
className={classes.gridWrap}
>
<Grid item xs={6}>
<Card className={classes.card}>
{language}
</Card>
...
【问题讨论】:
-
您是否在 componentWillReceiveProps 中设置状态。在componentWillMount中同步调用setState也不会触发额外的渲染
-
@ShubhamKhatri 我试过
componentWillMount、componentWillUpdate和componentWillReceiveProps,但都没有奏效 -
能否添加你的componentWillReceiveProps的相关代码
-
@ShubhamKhatri 它与我粘贴的代码完全相同
componentWillMount -
处理程序上的错字:` onChange={this.handleLanguaheChange} `... 编辑模式不允许我修复,除非我再编辑 5 个字符????
标签: javascript forms reactjs redux react-redux