저는 아직 JavaScript와 ReactJS를 사용하는 초보자입니다.
사용자가 수행하는 일부 작업을 보여주는 목록이 있습니다. 내가 알고 싶은 것은 사용자가 전달한 계정에 따라 총 작업을 계산하는 방법입니다.이 데이터를 어떻게 그룹화합니까?
예를 들어, 계정 사용자 유형 경우 A
두개의 트랜잭션 $5
및 $2
계정의 총 A
일 것이다 $7
. 그리고 그가 계정에 B
의 거래를 입력 $3
하면 계정의 총계는 B
이어야합니다. $3
아래 이미지를 통해 내가 의미하는 바를 더 쉽게 설명 할 수 있습니다.
그리고 여기에 내 코드가 있습니다.
내 ContextAPI :
import React from "react";
import PropTypes from "prop-types";
const AppContext = React.createContext();
const initialState = {
balance: 0,
transactions: []
};
const reducer = (state, action) => {
switch (action.type) {
case "ADD_TRANSACTION":
return {
...state,
balance: state.balance + action.payload.amount,
transactions: [
{
account: action.payload.account,
amount: action.payload.amount,
balance: state.balance + action.payload.amount
},
...state.transactions
]
};
default:
return state;
}
};
const AppContextProvider = ({ children }) => {
const [state, dispatch] = React.useReducer(reducer, initialState);
return (
<AppContext.Provider value={{ state, dispatch }}>
{children}
</AppContext.Provider>
);
};
AppContextProvider.propTypes = {
children: PropTypes.node.isRequired
};
export { AppContext, AppContextProvider };
내 거래 목록 :
import React from "react";
import { AppContext } from "../../providers";
const List = () => {
const { state } = React.useContext(AppContext);
return (
<div>
{state.transactions.map((transaction) => (
<div key={Math.random()} style={{ marginBottom: "10px" }}>
<div>
<span>
<strong>
{transaction.amount > 0 ? "Transferred" : "Withdrew"} $
{Math.abs(transaction.amount)}{" "}
</strong>{" "}
{transaction.amount > 0 ? "to " : "from "}
<strong>{transaction.account}</strong>.
</span>
</div>
<div>
<span>
Current <strong>{transaction.account}</strong>'s balance is{" "}
<strong>${Math.abs(transaction.balance)}</strong>.
</span>
</div>
</div>
))}
</div>
);
};
export default List;
도움을 주셔서 대단히 감사합니다 !!!
이제 기본적으로 각 계정의 잔액을 추적해야합니다. 따라서 다음과 같이 상태에 저장하십시오 (예 : 계정 a 및 b) :
balances: {"a": 10, "b": 20}
이제 새로운 거래를 추가 할 때 적절한 잔액을 더하거나 빼고 추적하십시오.
const initialState = {
balances: {},
transactions: []
};
const reducer = (state, action) => {
switch (action.type) {
case "ADD_TRANSACTION":
return {
...state,
balances: {
...state.balances,
[action.payload.account]: (state.balances[action.payload.account] || 0) + action.payload.amount
},
transactions: [
{
account: action.payload.account,
amount: action.payload.amount,
balance:
(state.balances[action.payload.account] || 0) + action.payload.amount
},
...state.transactions
]
};
default:
return state;
}
};
업데이트 된 샌드 박스 : https://codesandbox.io/s/thirsty-herschel-4j141
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다