gpt4 book ai didi

javascript - React 子组件未从父组件发送更新状态

转载 作者:行者123 更新时间:2023-11-28 03:09:46 25 4
gpt4 key购买 nike

我正在尝试遵循其官方网站上的 react 教程:https://reactjs.org/tutorial/tutorial.html

唯一的区别是我尝试仅使用功能组件来实现它,这是我在代码笔上的代码:

<强> 请参阅笔 React tutorial functional component作者:斯内登·贡萨尔维斯 (@snedden-gonsalves) 上CodePen

总结一下;我有一个简单的正方形组件,用于绘制各个正方形,一个父板组件,用于绘制 3x3 正方形板,以及一个总体游戏组件,用于维护状态,例如历史记录、当前正方形、当前回合等,如教程中所示。我目前将方 block 从父游戏组件发送到棋盘组件,如下所示:

<Board
onClick ={(i)=>{handleClick(i)}}
squares = {state.history[state.history.length - 1]}

/>

handleClick 创建新的方 block 状态并将其附加到历史数组中,我认为应该动态传递该数组,因为我还传递了数组中的最后一个条目,但看起来它根本没有将最后一个条目传递给子级成分。不确定发生了什么..

感谢您抽出时间。

组件:

正方形:

 const Square = (props)=>{
return(
<button className="square" onClick={(e)=>props.onClick()}>
{props.value}
</button>
)
}

董事会:

const Board = (props) => {
const renderSquare = (i)=>{
return <Square
value={props.squares[i]}
onClick={() => {
props.onClick(i)
}
}
/>
}
return(
<div>
<div className="board-row">
{renderSquare(0)}
{renderSquare(1)}
{renderSquare(2)}
</div>
<div className="board-row">
{renderSquare(3)}
{renderSquare(4)}
{renderSquare(5)}
</div>
<div className="board-row">
{renderSquare(6)}
{renderSquare(7)}
{renderSquare(8)}
</div>
</div>
)
}

游戏:

const Game = () =>{
let [state, setState] = useState({
history:[{
squares:Array(9).fill(null)
}],
isXNext:true,
status:'Next player X'
});

useEffect(() =>{
const currentSquares = state.history[state.history.length - 1].squares;
const winner = calculateWinner(currentSquares);
if(winner){
setState( state => ({...state, status:'Winner is ' + winner, ended:true}));
}
},[state.history]);


const handleClick = (i) =>{
const currentSquares = state.history[state.history.length - 1].squares;

if(state.ended || currentSquares[i])
return;

const newSquares = currentSquares.slice();
newSquares[i] = state.isXNext?'X':'O';

const newIsXNext = !state.isXNext;
const newHistory = state.history.concat([
{squares:newSquares}]);

setState(state => ({...state,
history: newHistory,
isXNext: newIsXNext,
status:'Next player ' + (newIsXNext?'X':'O')
}));

}

return(
<div className="game">
<div className="game-board">
<Board
onClick ={(i)=>{handleClick(i)}}
squares = {state.history[state.history.length - 1]}
/>
</div>
<div className="game-info">
<div>{state.status}</div>
<ol>{/* TODO */}</ol>
</div>
</div>
);
}

最佳答案

事实证明它传递了更新的状态,我没有使用正确的 key ,这就是我修复它的方法:

<Board
onClick ={(i)=>{handleClick(i)}}
squares = {state.history[state.history.length - 1].squares}/>

工作代码笔:

请参阅笔 React tutorial functional component Working作者:斯内登·贡萨尔维斯 ( @snedden-gonsalves) 上 CodePen

关于javascript - React 子组件未从父组件发送更新状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60240532/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com