提交后负责显示我所有交易的组件都没有更新

发布于 2025-02-11 03:44:11 字数 2960 浏览 1 评论 0原文

我使用的是带有React的Redux Toolkit并具有基本设置,因为我正在构建一个简单的费用跟踪器,因此我有两个操作:获取所有交易并添加新的交易。就是这样。

我的问题:创建新事务时,负责显示我的数据的组件不会更新,我只能在刷新页面后看到更改。 您可以在下面看到我的transactionslice文件:

const initialState = {
    transactions: [],
    loading: false,
    error: null,
}

export const getTransactions = createAsyncThunk(
    "transactions/getTransactions",
    async () => {
        const res = await axios.get('http://localhost:8000/transactions')
        return res.data
    }
)

export const addTransaction = createAsyncThunk(
    "transaction/addTransaction",
    async(data) => {
       const res = await axios.post('http://localhost:8000/transactions', data);
        return res.data
    }
)

const transactionsSlice = createSlice({
    name: 'transactions',
    initialState,
    reducers: {},
    extraReducers: {
        [getTransactions.pending]: (state) => {
            state.loading = true;
        },
        [getTransactions.fulfilled]: (state, {payload}) => {
            console.log(payload);
            state.loading = false;
            state.transactions = payload;
            state.error = ''
        },
        [getTransactions.rejected]: (state) => {
            state.loading = false;
            state.error = state.error.message;
        },
        [addTransaction.pending]: (state) => {
            state.loading = true;
        },
        [addTransaction.fulfilled]: (state) => {
            state.loading = false;           
        },
        [addTransaction.rejected]: (state) => {
            state.loading = false;
            state.error = state.error.message;
        }
    }
});

这是我显示所有交易的组件中的代码,

 const { transactions, loading } = useSelector(selectAllTransactions);
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(getTransactions());
  }, [dispatch]);

但是当我提出职位时,请求我的状态我的所有交易都不会立即更新。我只有在更新页面并且正在手动执行此页面时才能看到更改。我想知道,如果我有效果观察更改,为什么会发生这种情况?

AddTransaction.js文件:

const [transactionName, setTransactionName] = useState('');
  const [amount, setAmount] = useState('');

  const dispatch = useDispatch();

  const handleSubmit = (e) => {
    e.preventDefault();
    const data = {
      transactionName,
      amount
    }
    
    if(transactionName && amount){
      dispatch(addTransaction(data));
      dispatch(getTransactions());
      setTransactionName('')
      setAmount('');
    }

  }

我已经尝试使用Google Google,但是我的疑问似乎很愚蠢,以至于我什至找不到答案。 这是我的服务器文件:

app.post('/transactions',(req, res) => {
    const {transactionName, amount} = req.body;
    const query = `INSERT INTO transactions (title, amount) 
                        VALUES ("${transactionName}", "${amount}")`

    db.query(query, (err, result) => {
        if(err){
            console.log(err)
        }
        res.send(result)
    })
    
});

我缺少什么吗?有人可以向我解释为什么负责显示所有交易的组件在提交后没有更新?

I'm using redux toolkit with react and have a basic setup because I'm building a simple expense tracker, so I have two operations: get all transactions and add a new transaction. That's it.

My problem: When I create a new transaction the component responsible for displaying my data does not update and I can only see the changes after refreshing the page.
Below you can see my transactionSlice file:

const initialState = {
    transactions: [],
    loading: false,
    error: null,
}

export const getTransactions = createAsyncThunk(
    "transactions/getTransactions",
    async () => {
        const res = await axios.get('http://localhost:8000/transactions')
        return res.data
    }
)

export const addTransaction = createAsyncThunk(
    "transaction/addTransaction",
    async(data) => {
       const res = await axios.post('http://localhost:8000/transactions', data);
        return res.data
    }
)

const transactionsSlice = createSlice({
    name: 'transactions',
    initialState,
    reducers: {},
    extraReducers: {
        [getTransactions.pending]: (state) => {
            state.loading = true;
        },
        [getTransactions.fulfilled]: (state, {payload}) => {
            console.log(payload);
            state.loading = false;
            state.transactions = payload;
            state.error = ''
        },
        [getTransactions.rejected]: (state) => {
            state.loading = false;
            state.error = state.error.message;
        },
        [addTransaction.pending]: (state) => {
            state.loading = true;
        },
        [addTransaction.fulfilled]: (state) => {
            state.loading = false;           
        },
        [addTransaction.rejected]: (state) => {
            state.loading = false;
            state.error = state.error.message;
        }
    }
});

and here is the code from the component where I'm displaying all transactions

 const { transactions, loading } = useSelector(selectAllTransactions);
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(getTransactions());
  }, [dispatch]);

but when I make a post request my state with all transactions doesn't update immediately. I can only see the changes if I update the page and I'm doing it manually. I'm wondering why is this happening if I have useEffect watching for changes?

AddTransaction.js file :

const [transactionName, setTransactionName] = useState('');
  const [amount, setAmount] = useState('');

  const dispatch = useDispatch();

  const handleSubmit = (e) => {
    e.preventDefault();
    const data = {
      transactionName,
      amount
    }
    
    if(transactionName && amount){
      dispatch(addTransaction(data));
      dispatch(getTransactions());
      setTransactionName('')
      setAmount('');
    }

  }

I've tried to google it but it seems my doubt is so silly that I can't even find an answer for that.
Here is my server file:

app.post('/transactions',(req, res) => {
    const {transactionName, amount} = req.body;
    const query = `INSERT INTO transactions (title, amount) 
                        VALUES ("${transactionName}", "${amount}")`

    db.query(query, (err, result) => {
        if(err){
            console.log(err)
        }
        res.send(result)
    })
    
});

Am I missing something? Could someone explain to me why the component responsible to display all transactions are not updating after submit, please?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

南七夏 2025-02-18 03:44:11

尝试执行getTransactions一旦addtransaction(data)完成,而不是同时:

  const handleSubmit = (e) => {
    e.preventDefault();
    const data = {
      transactionName,
      amount
    }
    
    if(transactionName && amount){
      dispatch(addTransaction(data))
        .then(() => {
          dispatch(getTransactions())
          setTransactionName('')
          setAmount('')
        }
    }
  }

Try executing getTransactions once addTransaction(data) is finished, not at the same time:

  const handleSubmit = (e) => {
    e.preventDefault();
    const data = {
      transactionName,
      amount
    }
    
    if(transactionName && amount){
      dispatch(addTransaction(data))
        .then(() => {
          dispatch(getTransactions())
          setTransactionName('')
          setAmount('')
        }
    }
  }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文