IT이야기

이미 설정된 리액션 후크를 다른 값으로 설정하는 방법

cyworld 2022. 4. 6. 21:37
반응형

이미 설정된 리액션 후크를 다른 값으로 설정하는 방법

리액션 후크를 처음 사용하는데 내가 해결할 수 없는 문제를 우연히 발견했어.나는 그것을 사용하고 있다.formAmount그것을 저장하기 위한 입력값을 얻기 위해 후크를 걸다.state.amount그렇게 되면, 그 금액은 사용자가 숫자를 넣을 때마다 합계를 숫자로 줄여야 한다.문제는 앞으로 새로운 배열을 만들 수 없다는 점이다.onChange왜냐하면 그것은 키의 모든 스트로크를 목록화해서 완전한 번호를 나에게 주지 않고 내가 그것을 직접 설정할 수 없기 때문이다.state.amount어떻게 하면 그 양을 구해서 배열로 보관할 수 있을까?

내 암호는 다음과 같다.

const Transactions = () => {
    const [state, setState] = useState([
        {
            expense: [],
            amount: [],
            id: ''
        }

    ])

    const [formExpense, setFormExpense] = useState('')
    const [formAmount, setFormAmount] = useState([])



    const handleSubmit = (e) => {
        e.preventDefault();

        addExpense()
        e.target.reset()
    }
    // add total of array of amount
    let sum = formAmount.reduce((accumulator, currentValue) => {
        { return accumulator += currentValue }
    }, 0)

    // push value of input to array
    const addExpense = (e) => {

        setState([...state, { expense: formExpense, amount: [...formAmount], id: Math.random() * 100 }])

    }


    return (
        <div className="transactions">

            <div className="expenses">
                <form onSubmit={handleSubmit}>
                    <input
                        type="text"
                        id="expense"
                        className="formfield"
                        name="expense"
                        placeholder="Expense..."
                        onChange={(e) => setFormExpense(e.target.value)}
                    />
                    <input
                        type="text"
                        id="amount"
                        className="formfield"
                        name="amount"
                        placeholder="Amount..."
                        onChange={(e) => setFormAmount([Number(e.target.value)])}
                    />
                    <button type="submit">Submit</button>
                </form>
            </div>
            <div className="finalbalance ">

                <div className="finalexpense final">
                    Total Expense
                    {'$' + sum.toLocaleString()}
                    {
                        state.map(stat => {
                            return (

                                <div key={stat.id}>

                                    <h3 className="outputexpense output">{stat.expense + stat.amount}</h3>
                                </div>


                            )
                        })
                    }

                </div>
            </div>
        </div>


    )
}

여기에 답이 있다.나 역시 여기서 Fiddle을 했다.

function Transaction(props){

    const [listOfExpenses, setlistOfExpenses] = React.useState([]);
    const [expense, setExpense] = React.useState("");
    const [amount, setAmount] = React.useState(0);
    const [totalExpenditure, setTotalExpenditure] = React.useState(0);


    const handleInputChange = (hookSetterMethod) => (e) =>{
        let {value} = e.target;
        return hookSetterMethod(value);
    }

    const addExpense = (expenseObject) => {
        setlistOfExpenses([...listOfExpenses, expenseObject])
    }

    const getTotalExpenditure = (listOfExpenses) =>
    {
            if(listOfExpenses.length > 0)
        {
          let tempExpenseAmountList = listOfExpenses.map((expense, id)=>{
              if(expense.amount)
              {
                  return expense.amount;
              }else{
                  return 0;
              }
          });

          return tempExpenseAmountList.reduce((accumulator, currentVal)=>{
              return Number(accumulator) + Number(currentVal);
          })
        }
        return 0;
    }

    React.useEffect(()=>{
        setTotalExpenditure(getTotalExpenditure(listOfExpenses));
    }, [listOfExpenses])

    const handleFormSubmission = (e) =>{
        e.preventDefault();
        addExpense({
            amount,
            expense
        });
    }
    
    const renderExpenses = (expenseList) => {
      return expenseList.map((expense, id)=>{
        return (
          <tr key={id}>
            <td>{++id}</td>
            <td>{expense.expense}</td>
            <td>: ${expense.amount}</td>
          </tr>
        )
      });
    }

    return(
        <div>
            <div>
                <h1>Add your expenses below</h1>
                <form onSubmit={handleFormSubmission}>
                    <div>
                        <label>Expense</label>
                        <input value={expense} onChange={handleInputChange(setExpense)} />
                    </div>
                    <div>
                        <label>Amount</label>
                        <input value={amount} onChange={handleInputChange(setAmount)} />
                    </div>
                    <div>
                        <button type="submit">Add Expense</button>
                    </div>
                </form>
            </div>
            <hr />
            <div>
              <table>
                <tr>
                  <th>
                      <td>Id</td>
                      <td>Expense</td>
                      <td>Amount</td>
                  </th>
                </tr>
                {renderExpenses(listOfExpenses)}
                <tr className="total">
                  <td>Total Expenses</td>
                  <td>: ${totalExpenditure}</td>
                </tr>
              </table>
            </div>
        </div>
    );
}


ReactDOM.render(<Transaction />, 
document.getElementById("root"));
table{
  margin-top: 15px;
}

.total{
  display: table;
  border-top: 1px solid #434649;
  border-bottom: 2px double #434649;
  color: #f80000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script>
<div id="root"></div>

참조URL: https://stackoverflow.com/questions/63441259/how-can-i-set-react-hooks-to-another-value-when-it-is-already-set

반응형