在React.tsx中使用createContext传递useState



我已经定义了一个contextTransaction它接受一个对象和一个函数。在AppProvider事务。供应商返回。代码是GlobalState。tsx文件:

import { createContext, useState } from "react";
export interface IProviderProps {
children?: any;
}
type Cat = {
id: number;
text: string;
amount: number;
}
type Ca =Cat[]
export const initialState = {
state: [
{id:4, text:'hi', amount:234},
{id:3, text:'hd', amount:-234},
{id:1, text:'hs', amount:34}
],
setState: (state: Ca) => {}
}
console.log(initialState.state)
export const Transaction = createContext(initialState);
export const AppProvider = (props: IProviderProps) => {
const [state, setState] = useState(initialState.state);
console.log(state);
return <Transaction.Provider value={{state, setState}}>{props.children}</Transaction.Provider>;
};

在App.tsx中,我已经传递了提供者:

import React, { useState } from 'react';
import './App.css';
import { Header } from "./Components/Header";
import { Balance } from './Components/Balance';
import { IncomeExpense } from "./Components/Income_Expense";
import { TransactionHistory } from "./Components/TransactionHistory";
import { AddTransaction } from "./Components/AddTransaction";
import { AppProvider } from './Context/GlobalState'
function App() {
const [islit, setlit] = useState(true);

return (
<AppProvider>
<div className={`${islit? '': 'dark'} body`}>
<Header islit={islit} setlit={setlit} />
<div className="container">
<Balance />
<IncomeExpense />
<TransactionHistory />
<AddTransaction />
</div>
</div>
</AppProvider>
);
}
export default App;

我正试图用'setState'改变'state',但它不工作:

import React, { useState, useContext } from 'react';
import { Transaction} from '../Context/GlobalState';
export const AddTransaction = () => {
const initialState = useContext(Transaction);
const [Incexp, setIncExp] = useState('income');
const [text, settext] = useState('');
const [amount, setamount] = useState(0);
const transactions = initialState.state;
const settransaction = initialState.setState;
function Addition(e: any) {
e.preventDefault();
settext('');
setamount(0);
transactions.push({id:Math.floor(Math.random() * 100000000), text:text, amount:Incexp==='income'? +amount: -amount})
settransaction(transactions);
console.log(transactions);
}
return (
<div>
<h3>Add Transaction</h3>
<form onSubmit={Addition}>
<label htmlFor="description">Text</label>
<input type="text" id="description" placeholder="Enter description..." value={text} onChange={(e) => { settext(e.target.value) }} required />
<label htmlFor="amount">Amount</label>
<input type="number" id="amount" placeholder="Enter Amount..." value={amount === 0 ? '' : amount} onChange={(e) => { setamount(parseInt(e.target.value)) }} required />
<div className="Inc-Exp">
<div>
<input type="radio" id="income" name="balance" defaultChecked onClick={()=>{setIncExp('income')}}/>
<label htmlFor="income" className="inc-col">Income</label>
</div>
<div>
<input type="radio" id="expense" name="balance" onClick={()=>{setIncExp('expense')}}/>
<label htmlFor="expense" className="exp-col">Expense</label>
</div>
</div>
<input className="btn" type="submit" value="Addtransaction" />
</form>
</div>
)
}

另一个子组件:

import React, { useContext } from 'react';
import { Transaction } from '../Context/GlobalState';
export const Balance = () => {
const initialState = useContext(Transaction);
const transactions = initialState.state;
var total=0;
transactions.map((transaction) => total+=transaction.amount)
return (
<div>
<h4>Your Balance</h4>
<h1 className={`${total > 0 ? 'plus' : ''} ${total < 0 ? 'minus' : ''}`}>${total}</h1>
</div>
)
}

每次我点击一个按钮添加交易。我想让它更新状态。但是没有更新

状态未更新,因为您没有更改对象事务的引用,请按如下操作

function Addition(e: any) {
e.preventDefault();
settext('');
setamount(0);
settransaction([...transactions,{id:Math.floor(Math.random() * 100000000), text:text, amount:Incexp==='income'? +amount: -amount} ]);
console.log(transactions);
}

在这种情况下,你传递给settransaction的对象将有一个新的引用,反应将更新状态

请将setState更改为回调变体setState((previousState) => {...})

function Addition(e: any) {
e.preventDefault();
settext('');
setamount(0);
transactions.push({id:Math.floor(Math.random() * 100000000), text:text, amount:Incexp==='income'? +amount: -amount})
settransaction(transactions);
console.log(transactions);
}

function Addition(e: any) {
e.preventDefault();
settext('');
setamount(0);
settransaction((prevState) => {
return prevState.push({id:Math.floor(Math.random() * 100000000), text:text, amount:Incexp==='income'? +amount: -amount});
});
}

console.log可能不会显示更新的值,因为需要重新渲染才能获得更新的context值。

但是在context更新之后,将由react触发重新渲染,因此负责显示更新的statecomponent最终将显示更新的状态。

最新更新