无限循环导致浏览器冻结

问题描述 投票:0回答:1

我有以下状态

const [selectedUser, setSelectedUser] = useState(null); 

和输入

{users.map(user => (
    <input type="radio" id={user.key} name="users" value={user.id}
        onChange={() => console.log(user)} // setSelectedUser(user) - causes freeze
        checked={selectedUser !== null && selectedUser.id === user.id} />

))}

上面注释中的代码导致冻结,不知道为什么 setSelectedUser(user)

有问题
reactjs react-hooks
1个回答
0
投票

为了防止无限循环并修复冻结,您必须确保 onChange 处理程序仅在必要时更新状态,并且必须确保避免触发不必要的重新渲染。

import React, { useState } from 'react';

function UserSelection({ users }) {
    const [selectedUser, setSelectedUser] = useState(null);
    const handleChange = (user) => {
        setSelectedUser(user);
    };

    return (
        <div>
            {users.map(user => (
                <label key={user.key}>
                    <input 
                        type="radio" 
                        id={user.key} 
                        name="users" 
                        value={user.id}
                        onChange={() => handleChange(user)} 
                        checked={selectedUser !== null && selectedUser.id === user.id} 
                    />
                    {user.name} {/* here i am assuming that user object has a 'name' property */}
                </label>
            ))}
        </div>
    );
}

export default UserSelection;

© www.soinside.com 2019 - 2024. All rights reserved.