无法更改我们以更改组件状态

发布于 2025-02-09 05:43:12 字数 1079 浏览 1 评论 0原文

这是我的addBlog组件的代码。

import React, { useState } from "react";

function AddBlogs() {

const[state, setState] = useState({blogs:[]})


const AddAnother = () => {
    return (
        <div>
            <label>Topic</label>
            <input></input>
            <button onClick={addblog}>Add another topic</button>
        </div>
    );
}

const addblog = () =>{
    setState({
        blogs:[...state.blogs,<AddAnother></AddAnother>]
    });
    console.log("Hello");
}

return (
    <div>
        <form>
            
            <div>
                <label>Topic</label>
                <input></input>
                <button onClick={addblog}>Add another topic</button>
            </div>
            <div>
                {state.blogs}
            </div>
        </form>
    </div>
);
}
export default AddBlogs;

当我单击该添加另一个主题按钮 addanothere 组件仅需0.5秒或更少。有什么解决方案吗?

This is code of my AddBlog Component

import React, { useState } from "react";

function AddBlogs() {

const[state, setState] = useState({blogs:[]})


const AddAnother = () => {
    return (
        <div>
            <label>Topic</label>
            <input></input>
            <button onClick={addblog}>Add another topic</button>
        </div>
    );
}

const addblog = () =>{
    setState({
        blogs:[...state.blogs,<AddAnother></AddAnother>]
    });
    console.log("Hello");
}

return (
    <div>
        <form>
            
            <div>
                <label>Topic</label>
                <input></input>
                <button onClick={addblog}>Add another topic</button>
            </div>
            <div>
                {state.blogs}
            </div>
        </form>
    </div>
);
}
export default AddBlogs;

When I click that Add another topic button AddAnother components blinks for just 0.5 second or less. Any solution for this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

小霸王臭丫头 2025-02-16 05:43:12

我看到几件事会引起问题。首先,当您更新状态时,您不应使用当前状态。取而代之的是,您应该使用接受旧状态作为第一个参数的函数的setState,例如:

const addblog = () => {
    setState((oldState) => {
        return { blogs: [...oldState.blogs, <AddAnother />] };
    });
    console.log("Hello");
};

不过,这不会解决您的问题。您看到的问题是由于您在组件中没有钥匙。因此,请尝试一下:

const addblog = () => {
    setState((oldState) => {
        return { blogs: [...oldState.blogs, <AddAnother key={oldState.blogs.length} />] };
    });
    console.log("Hello");
};

正如David指出的那样,该表格也在发布,这也导致了部分问题。

I see a couple things that will cause problems. First, when you update state, you shouldn't use the current state. Instead, you should use the setState that accepts a function with the old state as the first parameter, such as the following:

const addblog = () => {
    setState((oldState) => {
        return { blogs: [...oldState.blogs, <AddAnother />] };
    });
    console.log("Hello");
};

This won't solve your problem, though. The issue you're seeing is due to you not having a key in your array of components. So try this:

const addblog = () => {
    setState((oldState) => {
        return { blogs: [...oldState.blogs, <AddAnother key={oldState.blogs.length} />] };
    });
    console.log("Hello");
};

As David pointed out, the form is also posting, which is causing part of the problem as well.

大姐,你呐 2025-02-16 05:43:12

因为&lt; form&gt;正在发布。如果您不需要 这是实际的&lt; form&gt;,则完全删除该元素。但是,如果出于某种原因要保留该元素,请更改按钮类型:

<button type="button" onClick={addblog}>Add another topic</button>

默认情况下a &lt; button&gt;是类型提交,除非另有说明。


编辑:此外,在这里回答,您需要更改设置状态的方式要使用回调过载:

setState((oldState) => {
    return { blogs: [...oldState.blogs, <AddAnother key={oldState.blogs.length} />] };
});

最多的情况下,无论您直接设置状态还是使用基于先前状态设置的回调,都没有什么区别。例如,在循环中排队多个状态更新时,通常会使用后者。但是您在这里有一个边缘箱。

您的addanother组件内部引用addblog的“陈旧版本”,该始终引用原始状态。更改为setState的回调版。

其他方法是重组代码以删除循环依赖性,重构组件中的离散代码,使用usecallback之类的工具来定义对状态值等有依赖性的功能。

Because the <form> is posting. If you don't need this to be an actual <form> then remove that element entirely. But if for some reason you want to keep that element, change the button type(s):

<button type="button" onClick={addblog}>Add another topic</button>

By default a <button> is of type submit unless otherwise specified.


Edit: Additionally, as answered here, you need to change the way you're setting state to use the callback overload:

setState((oldState) => {
    return { blogs: [...oldState.blogs, <AddAnother key={oldState.blogs.length} />] };
});

In most cases it makes little difference whether you set the state directly or use the callback which sets based on previous state. The latter is often used when queueing up multiple state updates in a loop, for example. But you have an edge case here.

Your AddAnother component internally references a "stale version" of addblog which always references the original state. Changing to the callback version of setState gets around this.

Other ways around this would be to restructure your code to remove the circular dependency, refactor components into their own discrete code, make use of tools like useCallback to define functions which have dependencies on state values, etc.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文