gpt4 book ai didi

javascript - 创建 React 组件的不同实例

转载 作者:行者123 更新时间:2023-12-04 10:08:31 31 4
gpt4 key购买 nike

我的问题很简单:如何创建 React 组件的不同实例?

我正在做一个练习,你必须创建一个投票系统:每个组件都有自己的投票数量。

我遇到的问题是每个组件共享相同数量的选票,而不是分开。

这是代码:

import React, { useState } from 'react';
import ReactDOM from 'react-dom';

const Anecdote = ({text}) =>
{
const [votes, setVotes] = useState(0);

return (
<React.Fragment>
<p>{text}</p>
<p>Votes: {votes}</p>
<button onClick={() => setVotes(votes + 1)}>vote</button>
</React.Fragment>
)
}

const App = (props) =>
{
const [selected, setSelected] = useState(0);

function randomizeAnecdote(){
setSelected(Math.floor(Math.random() * anecdotes.length));
}

return (
<div>
{props.anecdotes[selected]}
<br/>
<button onClick={() => randomizeAnecdote()}>press</button>
</div>
)
}

const anecdotes = [
React.createElement(Anecdote, {text:'If it hurts, do it more often'}),
React.createElement(Anecdote, {text:'Adding manpower to a late software project makes it later!'}),
React.createElement(Anecdote, {text:'The first 90 percent of the code accounts for the first 90 percent of the development time...The remaining 10 percent of the code accounts for the other 90 percent of the development time.'}),
React.createElement(Anecdote, {text:'Any fool can write code that a computer can understand. Good programmers write code that humans can understand.'}),
React.createElement(Anecdote, {text:'Premature optimization is the root of all evil.'}),
React.createElement(Anecdote, {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.'}),
]

ReactDOM.render(
<App anecdotes={anecdotes} />,
document.getElementById('root')
)

基本上,函数 randomizeAnecdote()选择一个随机的轶事与自己的文本一起显示。然而,即使在展示另一个轶事时,投票也不会改变。

例如,如果一个轶事有 10 票,而我按下按钮进行随机化,则 10 票会留在那里。

我怎样才能做到这一点 votes每个元素都是独一无二的?

最佳答案

要重置投票,您可以收听 textuseEffect每当它发生变化时,将投票设置为 0。

useEffect(() => {
setVotes(0)
}, [ text ])

此外,在测试时,我发现随机值与先前值相同的问题。因此,为此,您可以使用以下技巧:
function randomizeAnecdote(){
let randomValue = Math.floor(Math.random() * anecdotes.length);
randomValue = (randomValue === selected ? randomValue + 1 : randomValue) % anecdotes.length;
setSelected(randomValue);
}

下面是一个示例代码:

请注意,它解决了以下问题:
  • 重置 vote指望新的文本。
  • 修复了随机化函数,因此没有重复的值
  • 更新代码以将字符串保存在数组中而不是 React.Element


  • const { useState, useEffect } = React;

    const Anecdote = ({text}) => {
    const [votes, setVotes] = useState(0);

    useEffect(() => {
    setVotes(0)
    }, [ text ])

    return (
    <React.Fragment>
    <p>{text}</p>
    <p>Votes: {votes}</p>
    <button onClick={() => setVotes(votes + 1)}>vote</button>
    </React.Fragment>
    )
    }

    const App = ({anecdotes}) => {
    const [selected, setSelected] = useState(0);

    function randomizeAnecdote(){
    let randomValue = Math.floor(Math.random() * anecdotes.length);
    randomValue = (randomValue === selected ? randomValue + 1 : randomValue) % anecdotes.length;
    setSelected(randomValue);
    }

    return (
    <div>
    <Anecdote text={ anecdotes[selected] } />
    <br/>
    <button onClick={() => randomizeAnecdote()}>press</button>
    </div>
    )
    }

    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 90 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.',
    ]

    ReactDOM.render(
    <App anecdotes={anecdotes} />,
    document.getElementById('root')
    )
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js"></script>
    <div id='root' />



    更新代码以维护计数:

    其重置为 0 的原因是因为 useEffect正在将投票设置为 0关于文字的变化。如果你需要维护计数,你将不得不维护一个复杂的状态。

    在以下示例中,状态属于以下类型:
    [ key: string ]: number

    哪里 key是文本,值是计数。

    在理想的环境中,我会创建一个 redux 存储,以更详细的方式维护这两个值。但是对于示例,您可以创建一个 map<text, vote>并用它来显示/维护计数。

    const { useState, useEffect } = React;

    const Anecdote = ({text}) => {
    const [ myState, setMyState ] = useState({})

    useEffect(() => {
    if ( !myState[ text ] ) {
    const state = { ...myState }
    state[ text ] = 0;
    setMyState(state);
    }
    }, [ text ])

    const incrVote = () => {
    const state = { ...myState }
    state[ text ] = (state[ text ] || 0) + 1;
    setMyState(state);
    }

    return (
    <React.Fragment>
    <p>{text}</p>
    <p>Votes: {myState[ text ] || 0}</p>
    <button onClick={incrVote}>vote</button>
    </React.Fragment>
    )
    }

    const App = ({anecdotes}) => {
    const [selected, setSelected] = useState(0);

    function randomizeAnecdote(){
    let randomValue = Math.floor(Math.random() * anecdotes.length);
    randomValue = (randomValue === selected ? randomValue + 1 : randomValue) % anecdotes.length;
    setSelected(randomValue);
    }

    return (
    <div>
    <Anecdote text={ anecdotes[selected] } />
    <br/>
    <button onClick={() => randomizeAnecdote()}>press</button>
    </div>
    )
    }

    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 90 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.',
    ]

    ReactDOM.render(
    <App anecdotes={anecdotes} />,
    document.getElementById('root')
    )
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js"></script>
    <div id='root' />

    关于javascript - 创建 React 组件的不同实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61452729/

    31 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com