最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

reactjs - How to rerender only if the correct part of context state changes? - Stack Overflow

programmeradmin2浏览0评论

I have setup a state in the context using a reducer

const playerStateReducer = ((state: PlayerState, action: PlayerAction) => {
    switch (action.type) {
        case "SET_LOCATION": {
            return {...state, location: action.payload};
        }
        case "PICKUP_ITEM": {
           return {...state, inventory: [...state.inventory, action.payload]};
        }
        default:
            return state;
    }
});

And then context Provder is setup as const GameStateProvider = (props: any) => { const [playerState, playerStateDispatch] = useReducer(playerStateReducer, initialPlayerState);

const values = {
    playerState: playerState,
    playerStateDispatcher: playerStateDispatch,
};

return (
    <GameStateContext.Provider value={values}>{props.children}</GameStateContext.Provider>
);

}

I now have 2 memoized components. 1 for map and 1 for inventory. What i would like is that if player moves around, inventory is not re-rendered. And if something happens in inventory then map is not rerendered. Right now when player moves around, inventory component also gets re-rendered, even tho inventory has not changed.

const PlayerInventory = () => {
    const {playerState} = useGameState();

    return (
        <div className={'inventory-container'}>
            {playerState.inventory.map((item: IInventorySocket) => <InventoryItem item={item}/>)}
        </div>
    );
}

export default React.memo(PlayerInventory);

I understand this is because playerstate is updated so a totally new state causes the inventory component to re-render. What can i do to prevent unnessesary rerendering?

发布评论

评论列表(0)

  1. 暂无评论