我的阵列计数器落后1步。我该如何解决?

时间:2019-07-28 06:48:41

标签: reactjs

用户单击数字1-10,然后填充一个数组,然后将其显示为列表项。问题在于数组总是从0开始,这是状态最初设置的状态,然后数组在显示先前推入的数字时落后一步。

enter image description here

App.js

import React, { useState } from 'react';
import Scoreboard from './Components/Scoreboard'
import Pins from './Components/Pins'
import './App.css';

function App() {

  const [pinCount, setPinCount] = useState(0);
  const [scoresArr, setScoresArr] = useState([]);

  const addScore = (pins) => {
    setPinCount(pins)
    console.log(pinCount)
    scoresArr.push(pinCount)
  }

  return (
    <div className="App">
      pinCount = {pinCount}
      <Pins addScore={addScore}/>
      <Scoreboard scoresArr={scoresArr}/>
    </div>
  );
}

export default App;

Scoreboard.js

import React from 'react'

const Scoreboard = ({ scoresArr }) => {

    let id = 0;

    return (
        <div>
            <ul className='pagination'>
             {scoresArr.map((score) => (
                    <li key={id++} className='page-link'>
                        {score}
                    </li>   
                ))}
            </ul>
        </div>
    )
}

export default Scoreboard

Pins.js

import React from 'react'

const Pins = ({ addScore }) => {

    const pinsArr = [1,2,3,4,5,6,7,8,9,10];

    return (
        <div>
            <ul className='pagination'>
                {pinsArr.map((pins) => (
                    <li key={pins} className='page-item'>
                        <a onClick={() => addScore(pins)} className='page-link'>
                            {pins}
                        </a>
                    </li>   
                ))}
            </ul>

        </div>
    )
}

export default Pins

1 个答案:

答案 0 :(得分:3)

尝试避免强行改变状态。当您执行scoresArr.push()时,您将直接更改现有的状态值。这违反了React原则,并可能导致代码的视觉副作用,例如您的错误在做什么。

让我们使用您拥有的setScoresArr更新程序来代替突变状态。我们将为scoresArr提供一个全新的数组,以便我们的更改按预期出现。

import React, { useState, useEffect } from "react";
import Scoreboard from "./Scoreboard";
import Pins from "./Pins";
import ReactDOM from "react-dom";

function App() {
  const [pinCount, setPinCount] = useState(0);
  const [scoresArr, setScoresArr] = useState([]);

  const addScore = pins => {
    setPinCount(pins);
    setScoresArr([...scoresArr, pins]);
  };

  return (
    <div className="App">
      pinCount = {pinCount}
      <Pins addScore={addScore} />
      <Scoreboard scoresArr={scoresArr} />
    </div>
  );
}

export default App;

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

这是一个有效的示例:https://codesandbox.io/s/sharp-lake-e0e0n