javascript - 更新 React 中的状态 : array element nested in Object

标签 javascript reactjs

我正在尝试构建 onChange 搜索功能。在建议列表中,我的状态是这样的:

results: {
    page: 1,
    results: [
       {value: 'popularity.desc', label: 'Popularity Descending'},
       {value: 'popularity.asc', label: 'Popularity Ascending'},
       {value: 'new value', label: 'new label'},
       {value: 'vote_average.desc', label: 'Rating Descending'}
    ]
}

当用户选择{value: 'new value', label: 'new label'}对象时。

如何将对象移动到状态结果数组的第一个索引?

例如:选择对象后。状态应该是这样的:

results: {
    page: 1,
    results: [
       {value: 'new value', label: 'new label'},
       {value: 'popularity.desc', label: 'Popularity Descending'},
       {value: 'popularity.asc', label: 'Popularity Ascending'},
       {value: 'vote_average.desc', label: 'Rating Descending'}
    ]
}

我的想法是使用扩展运算符和过滤器,但我不知道如何实现。

选择项目方法:

onSuggestionSelected = (event, {suggestion, suggestionValue }) => {

    console.log('Selected', suggestion);  // {value: 'new value', label: 'new label'}

    if (suggestion.media_type === 'movie') {
        this.navigate('/search/movie', suggestionValue, suggestion);
    } else if (suggestion.media_type === 'tv') {
        this.navigate('/search/tv', suggestionValue, suggestion);
    } else {
        this.navigate('/search', suggestionValue, suggestion);
    }
};

选择后,将导航:

navigate = (pathname, queryValue, resultValue) => {

    // ResultValue is that Object that I want to shift first.

    this.props.history.push({ 
        pathname, 
        search: `?query=${queryValue}`, 
        state: {results: this.state.data}});
};

最佳答案

    //filtered the remaining item
    let remainValue = result.filter((obj, key) => obj.value != suggestion.value);
    //merge here 
    let newResult = [suggestion, ...remainValue]; //it will contain reordered item

关于javascript - 更新 React 中的状态 : array element nested in Object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51133430/

相关文章:

javascript - 如何使用列表渲染对象

javascript - 动态创建React组件

php - 如何从表格内容中获取记录作为弹出表单的数据并显示

javascript - 使用reactjs创建链接的覆盖

javascript - react : How to skip useEffect on first render

javascript - 对内部有两个对象的数组进行排序

javascript - 欧特克锻造 : Get access token using POST/XMLHttpRequest and Javascript?

javascript - Tinymce pragraph 标签 P 在保存数据时添加到文本区域

javascript - 字符串中的 html 删除样式内部 - 正则表达式

reactjs - REACT - 在渲染 APP 之前检查身份验证