簡體   English   中英

React - 如何使用當前狀態值作為變量,以便我可以將其設置為數組內的索引

[英]React - How to use the current state value as a variable so i can set as a index inside an array

我是 React 的新手,目前使用和對象的當前狀態作為另一個數組中的變量,該數組將從 0 開始填充,每次有人按下投票按鈕時,它會將 +1 存儲到所述數組索引。 我確信這是錯誤的方式,但我仍然試圖弄清楚是否可以使用我創建的邏輯。

感謝您的耐心!

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 App

首先,您需要一個數組來保存投票計數值,其次,在不可變更新中正確更新每個投票計數。

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>
  );
}

編輯 react-how-to-use-the-current-state-value-as-a-variable-so-i-can-set-as-a-index

您在 React 中更改的所有值都應該是響應式的,您永遠不應該直接更改值,因為它不會觸發重新渲染。 您應該使用useState鈎子。

在您存儲軼事投票的情況下,您可以創建一個長度為 6 的新數組,並用初始投票計數 - 0 填充它。然后您應該調用鈎子來更新計數。

 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>
  )

useState不返回一個對象,在這種情況下將返回一個number ,因為您傳入的默認值是0 您可以使用另一個useState來跟蹤每個軼事的投票值,即使您更改了軼事,分數也會保持不變。

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 anecdotesObjects = anecdotes.map(anecdote => ({ score: 0, anecdote }))

    const [selected, setSelected] = useState(0)
    const [scoredAnecdotes, setScoredAnecdotes] = useState(anecdotesObjects)

    return (
        <div>
            <h1>{anecdotes[selected]}</h1>
            <button onClick={() => setSelected(Math.floor(Math.random() * anecdotes.length))}>Next Anecdote</button>

            <button onClick={() => {
                setScoredAnecdotes(() => {
                    const aux = [...scoredAnecdotes]
                    aux[selected].score++;
                    return aux
                })
            }
            }>Vote</button>
            <p>votes: {scoredAnecdotes[selected].score}</p>
        </div>
    )
}

export default App

我認為,使用 useReducer 將幫助您將所有內容都放在一個地方:

 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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM