简体   繁体   English

React - 如何使用当前状态值作为变量,以便我可以将其设置为数组内的索引

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

I am pretty a new to React and currently to use the current state of and object as a variable in another array, said array will start filled with 0, and every time someone press the vote button it will store +1 to said array index.我是 React 的新手,目前使用和对象的当前状态作为另一个数组中的变量,该数组将从 0 开始填充,每次有人按下投票按钮时,它会将 +1 存储到所述数组索引。 I am sure its the wrong way but nevertheless I amtrying to figure out if is possible to use the logic i created.我确信这是错误的方式,但我仍然试图弄清楚是否可以使用我创建的逻辑。

Thanks for the patience!感谢您的耐心!

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

First, you'll need an array to hold the vote count values, and secondly, correctly update each vote count in an immutable update.首先,您需要一个数组来保存投票计数值,其次,在不可变更新中正确更新每个投票计数。

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

All values which you change in React should be reactive, you never should change a value directly, because it will not trigger re-rendering.您在 React 中更改的所有值都应该是响应式的,您永远不应该直接更改值,因为它不会触发重新渲染。 You should use useState hook.您应该使用useState钩子。

In your case to store the anecdotes votes you could create a new array with length 6 and fill it with initial votes count - 0. Then you should call the hook to update the counts.在您存储轶事投票的情况下,您可以创建一个长度为 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>
  )

The useState doest return an object, in this case will return a number , because the default value you are passing in is 0 . useState不返回一个对象,在这种情况下将返回一个number ,因为您传入的默认值是0 You can use another useState to track the value of the votes for each anecdote, even if you change of anecdote the score will stay.您可以使用另一个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

I think, using useReducer will help you keep everything in one place:我认为,使用 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