gpt4 book ai didi

javascript - 如何在 redux 状态更改时更新组件状态?

转载 作者:可可西里 更新时间:2023-11-01 01:43:45 25 4
gpt4 key购买 nike

因为我有一个带有表单的组件,所以我需要将表单连接到组件状态。初始数据来自 Redux,因此尝试通过使用 props 设置状态来初始化和更新组件:

componentWillMount = () => {
this.setState({
language: this.props.language || 'en'
})
}

language 是一个连接的 Prop ,我检查了它是否在商店中更新。

const mapStateToProps = state => ({
language: state.language
})

我也尝试过使用 componentWillReceivePropscomponentWillUpdate 但它不起作用。我得到初始状态,即使商店和连接的 Prop 发生变化,组件的状态也不会更新。

{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>
...

最佳答案

首先,您正在为 componentWillMount 使用箭头函数。经验法则是,不要将箭头函数用于生命周期 Hook (componentWillMount、shouldComponentUpdate 等)。通常在 componentWillMount Hook 中设置状态。但永远不要在 componentDidMount 中设置状态。请尝试将其重写为,

constructor(props) {
super(props)
this.state = {
language: 'en',
}
}
componentWillMount() {
const { language } = this.props
if (language) this.setState(prevState => ({ language: prevState.language = language }))
}

在一些特殊情况下,比如我在一个 .js 文件中写了两个类(就像我说的,有些异常(exception))并且我无法按预期从 componentWillMount 修改它(后来注意到, Prop 被修改了由子类)。在这种情况下,您可以在渲染中覆盖它

render() {
const { language } = this.props
if (language) this.setState(prevState => ({ language: prevState.language = language }))

关于javascript - 如何在 redux 状态更改时更新组件状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47695491/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com