避免使用promise进行递归渲染?

时间:2020-07-22 16:31:20

标签: javascript reactjs react-redux

这里是我简化的React组件:

import React from "react"
import {useSelector, useDispatch} from "react-redux"
import { useRouteMatch } from "react-router-dom"
import gameService from "../services/game"
import {setGame} from "../reducers/game" //action creator

const Game = () => {
    const game = useSelector(state => state.game)
    const dispatch = useDispatch()

    const match = useRouteMatch('/games/:id')
    gameService.oneGame(match.params.id).then(g => dispatch(setGame(g)))

    const gameInfo = (game) => {
        ...some proceessing
        return(JSX containig info about the game)
    }

    return(
        game ? <div>
            <h2>{game.name}</h2>
            {gameInfo(game)}
         </div> :
         loading
    )
} 

export default Game

从App.js中调用组件:

    <Route path="/games/:id">
        <Game />
    </Route>

一切正常,但网站呈现无限。在组件渲染后,promise是否会解析并再次渲染组件,或者这里发生了什么?最简单的解决方法是什么?

1 个答案:

答案 0 :(得分:3)

我认为您可能希望将对gameService的呼叫放在useEffect挂接中,以便仅在match.params.iddispatch更改时才调用,而不是每次组件被重新渲染。

尝试将其修改为:

import React, { useEffect } from "react"
import {useSelector, useDispatch} from "react-redux"
import { useRouteMatch } from "react-router-dom"
import gameService from "../services/game"
import {setGame} from "../reducers/game" //action creator

const Game = () => {
    const game = useSelector(state => state.game)
    const dispatch = useDispatch()

    const match = useRouteMatch('/games/:id')
    useEffect(() => {
         gameService.oneGame(match.params.id).then(g => dispatch(setGame(g)))
    }, [match.params.id, dispatch]);

    const gameInfo = (game) => {
        ...some proceessing
        return(JSX containig info about the game)
    }

    return(
        game ? <div>
            <h2>{game.name}</h2>
            {gameInfo(game)}
         </div> :
         loading
    )
} 

export default Game