handleChange中对象数组的setState不起作用



我使用弹性搜索在我的视图中进行搜索(ReactJs(。我创建了一个函数handleChange,根据我正在搜索的内容来更改表中数据的状态。所以到目前为止,我在我的代码中做到了这一点:

var esClient = new elasticsearch.Client({
host: 'localhost:9200',
log: 'info'
});
class MesExtraits extends Component {
constructor() {
super();
this.state = {
MP3info: [],
searchText: '',
}
}
updateSearch = (evt) => {
this.setState({ searchText: evt.target.value, });
var searchQ = evt.target.value;
var search_queryES = "titre:" + searchQ + "*"
esClient.search({
q: search_queryES
}).then(function (body) {
this.setState({ MP3info: body.hits.hits.map(i => i._source) })
console.log(this.state.MP3info)
console.log(body.hits.hits.map(i => i._source))
}.bind(this), function (error) {
console.trace(error.message);
});
};
render() {
const { MP3info } = this.state;
return (
<div>
<SearchBox styleName="gx-d-none gx-d-lg-block gx-lt-icon-search-bar-lg"
placeholder="Search in app..."
onChange={this.updateSearch.bind(this)}
value={this.state.searchText}
/>
<Paper className={classes.root}>
<Table className={classes.table} aria-label="simple table">
<TableHead>
<TableRow>
<TableCell><IntlMessages id="MP3.titre" /></TableCell>
<TableCell align="left"><IntlMessages id="MP3.descfiption" /></TableCell>
<TableCell align="left"><IntlMessages id="MP3.langue" /></TableCell>
<TableCell align="left"><IntlMessages id="MP3.stats" /></TableCell>
</TableRow>
</TableHead>
<TableBody>
{MP3info.map(row => (
<TableRow key={row.titre}>
<TableCell component="th" scope="row">
{row.titre}
</TableCell>
<TableCell align="left">{row.description}</TableCell>
<TableCell align="left">{row.langue}</TableCell>
<TableCell align="left"> <span id={row.idMedia} onClick={this.onClickPoup}><i class="icon icon-chart" /> </span> </TableCell>
</TableRow>
))}
</TableBody>
</Table>
</Paper>
</div>
);
}
}

问题是,当我在为MP3info设置State之后console.log(this.state.MP3info)时,它没有改变。如有任何帮助,我们将不胜感激。

setState是异步的。所以它会这样工作:

this.setState({ MP3info: body.hits.hits.map(i => i._source) }, () => {
console.log(this.state.MP3info)
})

来自文档:

setState((并不总是立即更新组件。它可能批处理或推迟更新。这使得阅读This.state就在调用setState((之后,这是一个潜在的陷阱。相反,使用componentDidUpdate或setState回调(setState(updater,callback((,其中任何一个都保证在更新后激发已应用。

调用setState后,不能期望立即更新状态,因为setState是一个异步操作。

但是,如果您想在更新状态后立即执行某些操作,则可以在setState中使用回调函数的第二个可选参数。

this.setState({
value: newStateValue,
}, () => {
const { value } = this.state; // access the updated value here
})

请遵循这个关于setState如何工作的美丽解释!链路

还有:

何时不使用回调:

React文档建议您使用生命周期事件。

原因如下。

CCD_ 3和CCD_。当道具和状态没有改变时,它们通过防止生命周期方法被触发来工作。

无论shouldComponentUpdate返回什么,setState回调都会触发。因此,即使状态没有改变,setState回调也会触发。

所以。。不要害怕使用setState回调。它在那里是有原因的。但当你这样做时,如果你看到任何狡猾的地方,请留意shouldComponentUpdate。

最新更新