简体   繁体   English

我如何处理更新 object 的 state,其中数据是从多个 React 源接收的?

[英]How do I handle updating the state of an object where data is received from multiple sources React?

Let's say I have an array of objects who's state I am interested in.假设我有一组我感兴趣的 state 对象。

Eg some data of the form:例如表格的一些数据:

const data = [{
    A: a,
    B: b,
    C: c,
    D: d
},...]

Let's assume that C and D are high cost query items, so for speed I load the page with A and B. Then, once I have A and BI go and fetch C and D items.假设 C 和 D 是高成本查询项,因此为了提高速度,我用 A 和 B 加载页面。然后,一旦我有 A 和 BI go 并获取 C 和 D 项。

I fetch all data again every... seconds, so that I have the most up to date values.我每隔...秒再次获取所有数据,以便我拥有最新的值。

fetchAB(); // Called every x seconds
fetchCD(); // Called every y seconds

I need to map these values to a component, which should update and show the most up to date values:我需要 map 这些值到一个组件,它应该更新并显示最新的值:

const SomeComponent = () => {
    const [data, setData] = useState([]);
    
    // Some fetch logic

    return(
        {
        data.map((d, idx) => {
            return (
            <key={idx}>
                <td>{d.A}</td>
                <td>{d.B}</td>
                <td>{d.C}</td>
                <td>{d.D}</td>   
            </> 
        )}
    )}
    )
}

How do I go about updating the state of an array of mapped objects which is being updated from two (or more) sources?我 go 如何更新从两个(或更多)源更新的映射对象数组的 state?

I found the best way to accomplish this was to convert my array of objects into an object of objects.我发现实现此目的的最佳方法是将我的对象数组转换为 object 个对象。

This way I can use direct mapping for previous states.这样我就可以对以前的状态使用直接映射。

Eg例如

// Displaying the data structure, not actually a const. Data is returned from an API fetch.

const data = {
    1 : {
        A: a,
        B: b,
        C: c,
        D: d
    },
    2: {
        A: a,
        B: b,
        C: c,
        D: d
    },...
}

Then I can update the state like so:然后我可以像这样更新 state:

var dataCD = fetchCD();
// Returns an object with id as the key, with "C, D" values.

var keys = Object.keys(dataCD);
for (var key in keys){
    data[key] = {
    ...data[key], // Include all previous data values in the object
    C: dataCD[key]["C"],
    D: dataCD[key]["D"] 
    }
}

The same logic must be implemented for all other methods updating the object state.必须为更新 object state 的所有其他方法实现相同的逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM