javascript - ReactJS:类型数组的状态在重新渲染期间被解构为元素

标签 javascript reactjs react-hooks react-component react-state

我正在尝试做什么

我有一个带有一系列“配置文件”的主要组件。对于每个配置文件,我有两个不同的条件组件(一次仅显示一个)。这两个组件中的每一个都有一个按钮,单击该按钮可以切换组件。因此,我已将状态提升到主组件,使用“useState” Hook 创建组件状态(这是一个数组,其中每个索引都是一个字符串,表示要为配置文件数组中的每个元素显示的子组件),我创建了两个函数来处理这些点击的事件,并将它们作为渲染 Prop 传递到其子组件中。

它们从第一个子组件开始。

问题以及我是如何发现它的

当您按下按钮切换到其他组件时,它就会起作用。当你按下返回按钮时,它崩溃了。说“类型错误:无法分配给字符串‘large’的只读属性‘0’”。我在 useState 初始化之后以及每个函数中的状态更改调用之后放置了一些 console.log(state) 。发生的情况(测试列表只有一个元素)是这样的

  1. 组件初始化时,状态显示为['正常'](原始状态,良好)
  2. 当单击第一个组件的按钮时,['normal'] 变为 ['large'](如预期)
  3. 现在重新渲染组件时,状态会变为“大”(不再是数组)
  4. 当单击第二个组件的按钮时,应用程序崩溃,因为它无法更改数组元素,因为它不再是数组

主要组件

const Peers = props => {
    let dummyPeer = {
        _id: "9asdf98sj3942j4fs9ji",
        user: {
            name: "Test Peer",
            avatar: "//www.gravatar.com/avatar/cd56136f6d9abfdf4a0198dc9ce656c8?s=200&r=pg&d=mm"
        },
        bio: "Biography for Test Peer",
        year: "2022",
        courses: [
            "CISC124",
            "PSYC223",
            "PSYC236",
            "COMM200",
            "CISC251"
        ]
    }

    let profiles = [];
    profiles.push(dummyPeer);

    let initialState = [];
    profiles.forEach(profile => {
        initialState.push("normal");
    });

    let [viewState, setViewState] = useState(initialState);
    console.log(viewState);

    const openLargeView = (id) => {
        let changeIndex = profiles.map(profile => profile._id).indexOf(id);
        setViewState(state => state[changeIndex] = "large");
        console.log(viewState);
    }

    const closeLargeView = (id) => {
        let changeIndex = profiles.map(profile => profile._id).indexOf(id);
        setViewState(state => state[changeIndex] = "normal");
        console.log(viewState);
    }

    return (
        <Fragment>
            {profiles.map((profile, index) => (<Fragment key={profile._id} >
                {viewState[index] === "normal" ? (
                    <Peer openLargeView={openLargeView} profile={profile} />
                ) : (
                    <ViewPeer closeLargeView={closeLargeView} profile={profile} />
                )}
            </Fragment>))}
        </Fragment>
    )
}

子组件 1:

const Peer = ({ profile, openLargeView }) => {
    const { _id, user, bio, year, courses } = profile;
    const { avatar } = user;

    return (<Fragment>
        <div className="card-row">
            <div className="profile-header">
                <h1 className="peer-text row-title"> {user.name} </h1>
                <p className="peer-text peer-small"> {year} </p>
                <img className="avatar avatar-peer-small" src={avatar} alt='' />
            </div>
            <button onClick={() => openLargeView(_id)} className="btn-small"> More </button>
        </div>
     </Fragment>)
}

子组件 2:

const ViewPeer = ({ profile, closeLargeView }) => {
    const { _id, user, bio, year, courses } = profile;
    const { avatar } = user;

    let courseElements = courses.map((course, index) =>
    <li key={index} className="profile-text"> {course} </li>
    );

    return (
        <Fragment>
            <div className="card-md peer-card">
                <div className="profile-header">
                    <h1 className="peer-text"> {user.name} </h1>

                    <img className="avatar avatar-peer" src={avatar} alt='' />
                </div>

                <div className="profile-info">
                    <h2 className="profile-text"> {bio} </h2>
                    <h2 className="profile-text2"> Year: {year} </h2>
                    <ul className="course-list"> {courseElements} </ul>

                    <div className="profile-button-group">
                        <button onClick={() => closeLargeView(_id)} className="btn-small"> Close </button>
                        <button className="btn-small"> Send Buddy Request </button>
                    </div>
                </div>
            </div>
            </Fragment>
    )
}

预期结果和实际结果

我希望当单击第一个组件的按钮时它会返回到原始组件,但状态会变成数组到字符串并且应用程序崩溃。

最佳答案

这里的问题是 viewStateopenLargeView()closeLargeView() 中更新的方式。

调用这些函数时,对 setViewState 的调用会调用状态更改回调,该回调实际上将 viewState 的类型从数组更改为字符串:

/* 
Summary of problem with following line of code:
1. The statement: state[changeIndex] = "large" returns the string "large"
2. When executed, the statement returns the "large" string from the callback
3. The viewState therefore becomes a string with value "large"
*/
setViewState(state => state[changeIndex] = "large"); 

考虑将这些状态更新修改为如下内容:

setViewState(state => {
    /* 
    1. Shallow clone state into a new array with ... spread
    2. Assign value of "large" to the "changeIndex" in cloned array
    3. Return cloned array as new state for viewState
    */
    const arrayClone = [...state];
    arrayClone[changeIndex] = "large";
    return arrayClone;
});

这可以确保通过 setViewState() 回调传回组件的状态是数组类型,这正是您的组件所期望的。显示是否需要进行所有更改的更完整示例如下:

const Peers = props => {

    const profiles = [{
        _id: "9asdf98sj3942j4fs9ji",
        user: {
            name: "Test Peer",
            avatar: "//www.gravatar.com/avatar/" + 
                    "cd56136f6d9abfdf4a0198dc9ce656c8?s=200&r=pg&d=mm"
        },
        bio: "Biography for Test Peer",
        year: "2022",
        courses: [
            "CISC124",
            "PSYC223",
            "PSYC236",
            "COMM200",
            "CISC251"
        ]
    }]

    let [viewState, setViewState] = useState(["normal"]);

    const openLargeView = (id) => {
        let changeIndex = profiles.map(profile => profile._id).indexOf(id);
        setViewState(state => {
            const arrayClone = [...state];
            arrayClone[changeIndex] = "normal";
            return arrayClone;
        });
    }

    const closeLargeView = (id) => {
        let changeIndex = profiles.map(profile => profile._id).indexOf(id);
        setViewState(state => {
            const arrayClone = [...state];
            arrayClone[changeIndex] = "large";
            return arrayClone;
        });
    }

    return (
        <Fragment>
            {profiles.map((profile, index) => (<Fragment key={profile._id} >
                {viewState[index] === "normal" ? (
                    <Peer openLargeView={openLargeView} profile={profile} />
                ) : (
                    <ViewPeer closeLargeView={closeLargeView} profile={profile} />
                )}
            </Fragment>))}
        </Fragment>
    )
}

希望有帮助!

关于javascript - ReactJS:类型数组的状态在重新渲染期间被解构为元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57485137/

相关文章:

javascript - redux-form - 仅提交编辑过的字段

javascript - 如何进行一个在检查元素外观之前等待 5 秒的测试(React 测试库)

javascript - 道场中的 "Cross-Select"?

javascript - 将用户输入存储在数组中

javascript - React - 如果用户没有权限,如何不在子组件内部运行函数

javascript - 这是检测 react 组件中第一次渲染的正确方法

javascript - 如何在孙子组件中设置或更新数组的状态

javascript - 使用 useState 的旧值更新数组值

javascript - 两个单独的 html 文件之间的平滑幻灯片过渡

javascript - 如何在 angularjs 中按字母和数字顺序对列表进行排序?