ReactJS-当父状态更新时,子道具不会更新/渲染

时间:2019-12-15 23:25:15

标签: javascript reactjs rendering state

简而言之: 我正在制作一个网页,以简化有时与中学生一起玩的游戏。我正在使用一个有状态的React组件将道具传递给孩子。问题在于,当父母的状态更新时,孩子的道具不会更新/渲染。我在这里查看了几个问题/答案,但似乎没有一个完全符合我的问题。我还制作了其他几个具有相同设置的网页,但从未遇到过此问题。我什至回过头来将此代码与我的其他一些“成功”项目进行了比较,但无法弄清与它有什么不同/使它不起作用。

更具体地说::我正在制作一个记分板,列出每个团队的码数,得分,以及该团队可以采取的行动的菜单按钮。一种这样的动作是“获得10码”。当前有一个按钮绑定到父组件“记分板”的功能“ gain10”。它将球队的码数增加10,最终将足球化身移动10码。我注意到,虽然它可以正确地更新父记分板的状态,但是码数统计在渲染中不会改变。按钮/增益10功能还更改了团队状态的“转弯”部分,应禁用该按钮,但不能这样做。在我看来,父项正在传递在构造函数中设置的初始道具,并且在setState()中调用gain10()进行更新后不重新渲染。不过,它们正在 进行更新。

代码被认为是混乱的,因为a)我不过是一个谦虚的数学老师,他非正式地学会了自己编写代码,并且b)这是我最初尝试做的事情的混合物(从状态传递整个团队对象)然后在创建子组件时将其分开)与在渲染时直接从状态传递信息。我可以继续讲下去,您可能会在这段代码中看到,但是让我们开始吧:

class Scoreboard extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      team1: {
        num: 1,
        yards: 10,
        score: 0,
        hasBall: true,
        turn: true,
        css: "top",
        ball: 'https://i.ibb.co/6n6bt0Y/football1.png',
        class: 'v-fb',
        style: {top: 2 + "em", left: 26.5 + "em"}
      },
      team2: {
        num: 2,
        yards: 20,
        score: 10,
        hasBall: true,
        turn: false,
        css: "top",
        ball: 'https://i.ibb.co/ngfTbLW/football2.png',
        class: 'v-fb',
        style: {top: 42.5 +"em", left: 21.5 + "em"}
      },
      team3: {
        num: 3,
        yards: 10,
        score: 0,
        hasBall: true,
        turn: false,
        css: "left",
        ball: 'https://i.ibb.co/vvWSCYW/football3.png',
        class: 'h-fb',
        style: {top: 42.5 +"em", left: 21.5 + "em"}
      },
      team4: {
        num: 4,
        yards: 10,
        score: 0,
        hasBall: true,
        turn: false,
        css: "left",
        ball: 'https://i.ibb.co/vDXmqb5/football4.png',
        class: 'h-fb',
        style: {top: 42.5 +"em", left: 21.5 + "em"}
      }
    }
    this.gain10 = this.gain10.bind(this)
  }

  gain10(e) {
    var id = e.target.id
    console.log(this.state.team1)
    this.setState((state) => {
      state[id].yards += 10
      state[id].turn = !state[id].turn
    })
  }

  render() {
    return(
      <div id="scoerboard">
        <TeamBoard team="team1" 
          yards = {this.state.team1.yards}
          score = {this.state.team1.score}
          turn = {this.state.team1.turn}
          teamData = {this.state.team1}
          func={this.gain10}/>
      </div>
    )
  }
}

const TeamBoard = (props) => {
  var id = `${props.team}-board`
  return (
    <div id={id}>
      <img src={props.teamData.ball} class={props.teamData.class} style={props.teamData.style}/>
      <p>team {props.teamData.num} stats</p>
      <p>
        <span class="board-label">Yards:</span> {props.yards}
        <span class="board-label">Score:</span> {props.score}
      </p>
      <button id={props.team} onClick={props.func} disabled={!props.turn}>go</button>
    </div>
  )
}

this pen上可以看到整个代码(亲爱的)和视觉效果,尽管正在积极地对其进行更改以继续尝试解决这一问题...

0 个答案:

没有答案
相关问题