无法通过父组件的回调函数看到子组件的更新(涉及数组和push操作)。

huangapple go评论64阅读模式
英文:

Cannot see updates from child component through parent's callback (case array and push)

问题

如题。我尝试通过父组件提供的回调从子组件设置组件状态。示例在 https://codepen.io/jadecubes/pen/wvYxKEL 中。

回调函数如下:

A = () => {
	const [info, setInfo] = useState(["Hello world."]);

	return (
		<>
			<B
				onChange={() => {/*这是回调*/
					info.length = 0;
					info.push("Hey!");
					setInfo(info);
				}}
			/>
			<h1>{info}</h1>
		</>
	);
};

点击按钮不会改变文本。但如果像下面这样,它会正常变化。

A = () => {
	const [info, setInfo] = useState(["Hello world."]);

	return (
		<>
			<B
				onChange={() => {/*这是回调*/
					setInfo(['hey']);
				}}
			/>
			<h1>{info}</h1>
		</>
	);
};

欢迎提出任何建议。

英文:

As title. I try to set component state from child through callback given by parent. Demo is in https://codepen.io/jadecubes/pen/wvYxKEL

The callback looks like

A = () =&gt; {
	const [info, setInfo] = useState([&quot;Hello world.&quot;]);

	return (
		&lt;&gt;
			&lt;B
				onChange={() =&gt; {/*I am callback*/
					info.length = 0;
					info.push(&quot;Hey!&quot;);
					setInfo(info);
				}}
			/&gt;
			&lt;h1&gt;{info}&lt;/h1&gt;
		&lt;/&gt;
	);
};

Clicking button doesn't change the text. But if it's something like below, it changes normally.

A = () =&gt; {
	const [info, setInfo] = useState([&quot;Hello world.&quot;]);

	return (
		&lt;&gt;
			&lt;B
				onChange={() =&gt; {/*I am callback*/
					setInfo([&#39;hey&#39;]);
				}}
			/&gt;
			&lt;h1&gt;{info}&lt;/h1&gt;
		&lt;/&gt;
	);
};

Any suggestions are welcome.

答案1

得分: 1

不能使用push方法向存储在React状态中的数组推送项目,因为React状态中的数组是不可变的。这是更新后的代码。请尝试:

const { useState, useEffect } = React;

A = () => {
    const [info, setInfo] = useState(["Hello world."]);

    return (
        <>
            <B
                onChange={() => {
                    setInfo([
                        ...info,
                        "Hey!"
                    ]);
                }}
            />
            <h1>{info}</h1>
        </>
    );
};

B = (props) => {
    return (
        <>
            <button
                type="button"
                onClick={() => {
                    props.onChange();
                }}
            >
                Click Me!
            </button>
        </>
    );
};

const root = ReactDOM.createRoot(document.querySelector("#root"));
root.render(<A />);

您可以在react文档中详细了解如何更新数组。

英文:

You can't push items in the array that is stored in react state with push method because arrays store in react state are immutable. Here is the updated code. Try that:-

const { useState, useEffect } = React;

A = () =&gt; {
	const [info, setInfo] = useState([&quot;Hello world.&quot;]);

	return (
		&lt;&gt;
			&lt;B
				onChange={() =&gt; {
					setInfo([
                      ...info,
                      &quot;Hey!&quot;
                    ]);
				}}
			/&gt;
			&lt;h1&gt;{info}&lt;/h1&gt;
		&lt;/&gt;
	);
};

B = (props) =&gt; {
	return (
		&lt;&gt;
			&lt;button
				type=&quot;button&quot;
				onClick={() =&gt; {
					props.onChange();
				}}
			&gt;
				Click Me!
			&lt;/button&gt;
		&lt;/&gt;
	);
};

const root = ReactDOM.createRoot(document.querySelector(&quot;#root&quot;));
root.render(&lt;A /&gt;);

You can read how to update arrays more in details in react docs.

Hope it will be helpful.

答案2

得分: 1

React状态是不可变的。

不应该尝试通过调用push、pop等方法直接更改状态。

应该使用返回新数组的方法,如concat等。

请查阅React文档:

https://react.dev/learn/updating-arrays-in-state

英文:

React state are immutable.

You should not aim to mutate the state directly by calling methods like push, pop

You should use methods that return new arrays like concat, …etc

Check React documentations below:

https://react.dev/learn/updating-arrays-in-state

huangapple
  • 本文由 发表于 2023年5月14日 14:41:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/76246183.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定