变量更新时 React 组件不重新渲染,渲染必须依赖于变量不为 null

React component not re-rendering when variable updates, rendering must depend on variable not being null

PlayerNumber 组件的代码最终将一个值赋给一个名为“sender”的空变量。最后,它更新了一个模拟状态,因此 Main 组件被迫更新,或者我是这么想的。尽管 sender 变量正确更新,PlayerNumber 组件仍然显示在 Main 组件中。

这是 PlayerNumber 组件代码:

const PlayerNumber = () => {

const [radio, setRadio] = useState(null)
const [garbage, setGarbage] = useState(0)

return (
    <div>
        <div>
            <header>
                <h1 className="center">players {radio} & sender {sender}</h1>
                </header>
                <div className="water">
                <h2>Select # of Players</h2>
                <form className="horizontal" onChange={(event) => setRadio(parseInt(event.target.value))}>
                <div className="royal">
                    <input name="jk" id="one" value="1" type="radio"  />
                    <label htmlFor="one"> 1 </label>
                </div>
                <div className="royal">
                    <input name="jk" id="two" value="2" type="radio"  />
                    <label htmlFor="two"> 2 </label>
                </div>
                <div className="royal">
                    <input name="jk" id="three" value="3" type="radio" />
                    <label htmlFor="three"> 3 </label>
                </div>
                <div className="royal">
                    <input name="jk" id="four" value="4" type="radio" />
                    <label htmlFor="four"> 4 </label>
                </div>
                </form>
                <br />
                <button className="fire" onClick={() => {
                    sender = radio
                    setGarbage(garbage + 1)
                    }}>✔️OK</button>
            </div>
        </div>
    </div>
)}

这是主要组件代码:

function Main() {
    
    return (
        <div>
        {!sender && <PlayerNumber /> }
        </div>
    )}

变量 sender 在组件外部定义为 null

最后,我使用了这个解决方案: React: How to render a parent component from child component?

只有,面向钩子的代码:

function Main() {
    const [index, setIndex] = useState(0)
    return (
        <div>
        {!sender && <PlayerNumber setIndex={i => setIndex(i)} /> }
        <p>{index}</p>
        </div>
    )}

然后在子组件中

<button className="fire" onClick={() => {
                    sender = radio
                    props.setIndex(5)
                    }}>✔️OK</button>