状态改变时,功能组件不执行其视觉更新。
我提供了一个组件的最小示例,其中我设置了新状态,但是该组件在浏览器中未更新。
import * as React from "react"
import { Button, makeStyles, Grid, TextField, createStyles } from '@material-ui/core'
import ReactDOM from "react-dom";
const styles = makeStyles(theme => createStyles({
container: {
display: 'flex',
flexWrap: 'wrap',
},
textField: {
marginLeft: theme.spacing(1),
marginRight: theme.spacing(1),
},
button: {
margin: theme.spacing(1),
}
}))
export interface RTestData {
title: string
}
interface Props {
data: RTestData[]
}
const testData: RTestData[] = [{title: "AA"}, {title: "BB"}, {title: "CC"}, {title: "DD"}, {title: "EE"}]
export const RTestContainer: React.FunctionComponent<Props> = (props) => {
const [count, setCount] = React.useState(0)
const [data, setData] = React.useState(props.data[count])
const classes = styles()
const handleClick = () => (e: React.MouseEvent<HTMLButtonElement, MouseEvent>) => {
console.log(`BUTTON click`)
const target = e.target
setCount(count + 1)
setData(props.data[count])
console.log("data " + JSON.stringify(props.data) + " ->" + JSON.stringify(data))
}
return (
<Grid container spacing={2}>
<Grid item xs={12}>
<RTestForm title={data.title}/>
</Grid>
<Grid item>
<Button
variant="contained"
color="primary"
className={classes.button}
onClick={handleClick()}
>
Next!!
</Button>
</Grid>
</Grid>
)
}
export const RTestForm: React.FunctionComponent<RTestData> = (props) => {
const [title, setTitle] = React.useState(props.title)
const handleChange = () => (e: React.ChangeEvent<HTMLInputElement>) => {
const target = e.target
const value = target.value
console.log("Title change ->" + title)
setTitle(value)
}
const classes = styles()
return (
<form className={classes.container} noValidate autoComplete="off">
<Grid container spacing={2}>
<Grid item xs={12} sm={6} lg={6}>
<TextField
required
label="Title"
value={title}
onChange={handleChange()}
className={classes.textField}
margin="normal"
variant="filled"
/>
</Grid>
</Grid>
</form>
)
}
ReactDOM.render(<div id="root">
<RTestContainer data={testData}/>
</div>, document.getElementById('root'));
单击按钮应选择并显示下一个数据项,例如G。文本字段显示“ AA”,“ BB”等。
在handleClick
上,您更改了RTestContainer
状态,但不影响RTestForm
状态。
// v On handleClick changes `data` state
<RTestForm title={data.title} />
// Changing props won't re-initial the state. v
const [title, setTitle] = React.useState(props.title);
尝试为props.title
的useEffect
更改添加监听器:
export const RTestForm: React.FunctionComponent<RTestData> = props => {
const [title, setTitle] = React.useState(props.title);
React.useEffect(() => {
setTitle(props.title);
}, [props.title]);
return <>...</>
};