gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 06:44:23 26 4
gpt4 key购买 nike

我使用elasticsearch在我的 View 中进行搜索(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>
);
}
}

问题是当我在 setState for MP3info 之后 console.log(this.state.MP3info) 它没有改变。任何帮助将不胜感激。

最佳答案

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

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

来自文档:

setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall. Instead, use componentDidUpdate or a setState callback (setState(updater, callback)), either of which are guaranteed to fire after the update has been applied.

关于arrays - handleChange 中对象数组的 setState 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58858114/

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