问题是状态filterArray仅在第二次单击按钮“Обучить”时才从null更改。为什么?
我真的需要它从一开始就可以正常工作。问题不在我打电话的对话框中。函数parse输入是解析输入,以捕获结尾带有*的单词。
第一次单击将调用对话框,但状态仅从第二次更改。
class Content extends React.Component {
constructor(props) {
super(props);
// initial state
this.state = {
textInput: "",
filterArray: [],
projectID: "",
entity: "",
synonyms: ""
};
this.dialog = React.createRef()
}
clear = () => {
// return the state to initial
this.setState({
textInput: "",
filterArray: []
});
};
updateIdandEntity = (value1, value2) => {
this.setState({ projectID: value1, entity: value2 })
}
parseInput = () => {
let tempArray = this.state.textInput.split(" "); // `convert string into array`
let newArray = tempArray.filter(word => word.endsWith("*"));
let filterArray = newArray.map(word => word.replace('*', ''));
this.setState({filterArray});
this.dialog.current.handleClickOpen()
};
render() {
return (
<Paper style={{maxWidth: 936, marginLeft: "250px", overflow: "hidden"}}>
<AppBar position="static" color="default" elevation={0}>
<Toolbar>
<Grid container spacing={16} alignItems="center">
<Grid item xs>
<TextField
fullWidth
placeholder="Введите фразу которую нужно обучить"
id="textInput"
InputProps={{
disableUnderline: true
}}
value={this.state.textInput}
onChange={e => {
this.setState({textInput: e.target.value});
}}
/>
</Grid>
<Grid item>
<DialogProject ref={this.dialog} data={this.state.filterArray} updateIdandEntity={this.updateIdandEntity}/>
<Button
variant="contained"
color="primary"
style={{
background:
"linear-gradient(45deg, #00ACD3 30%, #00BE68 90%)"
}}
onClick = {this.parseInput}
>
Обучить
</Button>
答案 0 :(得分:0)
似乎您对setState()的异步性有疑问。 setState有第二个可选参数,它是一个回调函数。 只需将对话框添加到setState()的回调函数中即可。
this.setState({filterArray}, () => {this.dialog.current.handleClickOpen()})
更新
parseInput = async () => {
console.log(this.state.textInput)
let tempArray = this.state.textInput.split(" "); // `convert string into array`
let newArray = tempArray.filter(word => word.endsWith("a"));
let filterArray = newArray.map(word => word.replace('a', 'b'));
await this.setState({filteArray: filterArray})
this.dialog.current.handleClickOpen()
};
好,您需要在此处添加异步和等待。应该这样做。