Soy bastante nuevo en React y actualmente uso el estado actual de un objeto como una variable en otra matriz, dicha matriz comenzará a llenarse con 0, y cada vez que alguien presione el botón votar, almacenará +1 en dicho índice de matriz. Estoy seguro de que es el camino equivocado pero, sin embargo, estoy tratando de averiguar si es posible usar la lógica que creé.
¡Gracias por la paciencia!
import React, { useState } from 'react' const App = () => { const anecdotes = [ 'If it hurts, do it more often', 'Adding manpower to a late software project makes it later!', 'The first 90 percent of the code accounts for the first 10 percent of the development time...The remaining 10 percent of the code accounts for the other 90 percent of the development time.', 'Any fool can write code that a computer can understand. Good programmers write code that humans can understand.', 'Premature optimization is the root of all evil.', 'Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.', 'Programming without an extremely heavy use of console.log is same as if a doctor would refuse to use x-rays or blood tests when diagnosing patients' ] const [selected, setSelected] = useState(0) var ary = new Uint8Array(10); //console.log('this', this.state); //show 1 anecdote //when user press next its generates a random number beetween 0 and 6 to display the anecdote //issue: //how to add said random value to my arrays so I can use the array to store the votes of each anecdote return ( <div> <h1>{anecdotes[selected]}</h1> <button onClick={ () => setSelected(Math.floor(Math.random() * 6) ) }>Next Anecdote</button> <button onClick={ () => ary[selected.state] + 1 }>Vote</button> <p>votes: {ary[selected.state]}</p> </div> ) } export default AppEn primer lugar, necesitará una matriz para contener los valores de conteo de votos y, en segundo lugar, actualice correctamente cada conteo de votos en una actualización inmutable.
export default function App() { const [selected, setSelected] = useState(0); // create vote counts array from anecdotes array and initialize to zeros const [votes, setVotes] = useState(Array.from(anecdotes).fill(0)); return ( <div> <h1>{anecdotes[selected]}</h1> <button onClick={() => setSelected( // use anecdote array length Math.floor(Math.random() * anecdotes.length)) } > Next Anecdote </button> <button onClick={() => setVotes((votes) => // immutable update, map previous state to next votes.map((count, index) => index === selected ? count + 1 : count ) ) } > Vote </button> <p>votes: {votes[selected]}</p> // display selected anecdote vote count </div> ); }Todos los valores que cambie en React deben ser reactivos, nunca debe cambiar un valor directamente, ya que no activará la reproducción. Deberías usar el gancho useState .
En su caso, para almacenar los votos de las anécdotas, podría crear una nueva matriz con una longitud de 6 y llenarla con el recuento inicial de votos: 0. Luego, debe llamar al gancho para actualizar los recuentos.
const [votes, setVotes] = useState(new Array(6).fill(0)); return ( <div> <h1>{anecdotes[selected]}</h1> <button onClick={ () => setSelected(Math.floor(Math.random() * 6) ) }>Next Anecdote</button> <button onClick={ () => { setVotes(prevVotes => { const upd = [...prevVotes]; upd[selected] += 1; return upd; })} }>Vote</button> <p>votes: {votes[selected]}</p> </div> )Creo que usar useReducer te ayudará a mantener todo en un solo lugar:
import React, { useState, useReducer } from "react"; const initialState = [ { text: "If it hurts, do it more often", votes: 0 }, { text: "Adding manpower to a late software project makes it later!", votes: 0 }, { text: "The first 90 percent of the code accounts for the first 10 percent of the development time...The remaining 10 percent of the code accounts for the other 90 percent of the development time.", votes: 0 }, { text: "Any fool can write code that a computer can understand. Good programmers write code that humans can understand.", votes: 0 }, { text: "Premature optimization is the root of all evil.", votes: 0 }, { text: "Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.", votes: 0 }, { text: "Programming without an extremely heavy use of console.log is same as if a doctor would refuse to use x-rays or blood tests when diagnosing patients", votes: 0 } ]; const reducer = (state, action) => { if (action.type === "VOTE_UP") { return state.map((item, index) => { if (index === action.index) { item.votes = item.votes + 1; } return item; }); } }; const App = () => { const [anecdotes, dispatch] = useReducer(reducer, initialState); const [selectedIndex, setSelectedIndex] = useState(0); return ( <div> <h1>{anecdotes[selectedIndex].text}</h1> <button onClick={() => { setSelectedIndex(Math.floor(Math.random() * 6)); }} > Next Anecdote </button> <button onClick={() => { dispatch({ type: "VOTE_UP", index: selectedIndex }); }} > Vote </button> <p>votes: {anecdotes[selectedIndex].votes}</p> </div> ); }; export default App;