1

为什么一个承诺会导致多次重新渲染?

我的主要问题是ForwardandGoalie函数都依赖于formationand starters

我在这里使用一个承诺来模拟我的应用程序对我的后端服务进行 api 调用。

IE

  const pickFormation = (formation) => {
    axios.get(`http://localhost:3000/games/${gameId}/starting-lineup/?formation=${formation}`, { headers:
      { Authorization: provider.token }
    })
      .then(res => {
        setStarters(res.data.starters)
        setFormation(formation)
      })
  }

下面是用于重新创建我的问题的代码示例。奇怪的是,如果我删除承诺,更新这两个状态都会起作用。有了承诺,有没有办法在所有状态对象都更新后只渲染一次?

import * as React from "react";
import { useState } from "react";
import { render } from "react-dom";

const App = () => {

  const [formation, setFormation] = useState('4-4-2');
  const [starters, setStarters] = useState({goalie: {name:'anthony'}});


  const updateFormation = (f) => {
    var promise1 = Promise.resolve();

    promise1.then(function () {
      setFormation(f)
      setStarters({ forward: { name: 'john' } });
    });


    // setFormation(f) this works perfectly with no promise. 
    // setStarters({ forward: { name: 'john' } });

  }

  const players = () => {
    switch(formation) {
      case '4-3-3':
        debugger;
        return <Forward starters={starters} />
      default: 
        return <Goalie starters={starters} />
    }
  }
  return (
    <div>
      <p>{formation}</p>
      <button onClick={() => updateFormation('4-3-3')}> update</button>
      {players()}
    </div>
  )
}

const Forward = ({starters}) => {
  return (
    <div>
      <p>{starters.forward.name[0]}</p>
    </div>
  )
}
const Goalie = ({starters}) => {
  return (
    <div>
      <p>{starters.goalie.name}</p>
    </div>
  )
}

render(<App />, document.getElementById("root"));

如果我删除承诺,它不会出现问题。如果承诺在那里,我会得到“TypeError:无法读取未定义的属性'名称'”。

4

0 回答 0