Obtengo los datos en forma de matriz y uso el método .map() para administrar un estado. Quiero crear una matriz que cambie los valores individualmente, pero siga moviéndose como uno solo. Ayúdame.
function Follow() { const [isFollow, setIsFollow] = useState([]); const handleChangeButton = idx => { const newIsFollow = [...isFollow]; newIsFollow[idx] = !newIsFollow[idx]; setIsFollow(newIsFollow); }; return ( <FollowWrapper> <Title> <h5>follw</h5> </Title> <ul ref={ref}> {users.map((info, idx) => { return ( <li key={idx}> <UserContainer> <UserInfo onClick={() => moveDetailPage(info.product_seq)}> <UserImage /> <TextWrapper> <p> <strong>{info.homepage_name}</strong> <br /> {info.wholesale_client_id} </p> </TextWrapper> </UserInfo> <ButtonWrapper> <FollowButton isFollow={isFollow[users.length - 1]} value={users.length - 1} onClick={() => { handleChangeButton(users.length - 1); }} > follw </FollowButton> </ButtonWrapper> </UserContainer> </li> ); })} </ul> <NavHeightBox /> </FollowWrapper> ); }¿Cómo puedo obtener los datos y gestionar los valores de estado de forma individual? Traté de designar el valor del estado individualmente, pero no parece una buena manera porque no sé cuántos datos ingresarán.
Parece que no está pasando el valor de "índice" correcto a sus accesorios FollowButton o handleChangeButton . De hecho, está pasando el último índice ( users.length - 1 ) a todos ellos. Utilice el valor idx asignado.
const handleChangeButton = idx => { const newIsFollow = [...isFollow]; newIsFollow[idx] = !newIsFollow[idx]; // <-- passed index setIsFollow(newIsFollow); }; ... {users.map((info, idx) => { // <-- current index return ( <li key={idx}> <UserContainer> ... <ButtonWrapper> <FollowButton isFollow={isFollow[idx]} // <-- current index value={idx} // <-- current index onClick={() => { handleChangeButton(idx); // <-- current index }} > follow </FollowButton> </ButtonWrapper> </UserContainer> </li> ); })} Dado que la matriz isFollow está inicialmente vacía, puede actualizar cualquier índice que desee y generará "agujeros" undefined en la matriz hasta que los "llene" alternando el valor allí. undefined es un valor falso, por lo que la negación es un valor verdadero. Si lo desea, puede inicializar el estado isFollow para que coincida con la matriz de users .
const [isFollow, setIsFollow] = useState(Array(users.length).fill('N'));...
const handleChangeButton = idx => { const newIsFollow = [...isFollow]; newIsFollow[idx] = newIsFollow[idx] === "Y' ? 'N' : 'Y'; setIsFollow(newIsFollow); }; En mi opinión, sería más simple y más trivial simplemente mantener isFollow un tipo booleano para alternar fácilmente y derivar en la interfaz de usuario cuál debería ser el valor "Y"/"N" de los valores de estado booleanos.