React useEffect not triggered



我的useEffect代码如下所示:

useEffect(() => {
if (user) {
setBalance(user.user_balance);
console.log("user.user_balance");
console.log(user.user_balance);
}
}, [user]);

完整代码:https://pastebin.com/CP6sLNQZ

useEffect应该在每次用户(user_balance(在数据库中更新时触发,但它没有被触发。用户是一个道具,它从redux传递到组件。

更新余额的操作如下:

import axios from "axios";
import { returnErrors } from "./errorActions";
import { UPDATE_BALANCE_SUCCESS } from "./types";
//update balance
export const updateBalance = ({ email, user_balance }) => (dispatch) => {
// Headers
const config = {
headers: {
"Content-Type": "application/json",
},
};
// Request body
const body = JSON.stringify({ email, user_balance });
axios
.post("/api/users/updatebalance", body, config)
.then((res) =>
dispatch({
type: UPDATE_BALANCE_SUCCESS,
payload: { email, user_balance },
})
)
.catch((err) =>
dispatch(returnErrors(err.response.data, err.response.status))
);
};

减速器:

import { UPDATE_BALANCE_SUCCESS } from "../actions/types";
const initalState = {
email: null,
user_balance: null,
};
export default function (state = initialState, action) {
switch (action.type) {
case UPDATE_BALANCE_SUCCESS:
return {
...state,
email: action.payload.email,
user_balance: action.payload.user_balance,
};
}
}

终点:

// @route       POST api/users/updatebalance
// @description Update user balance
// @access      Public
router.post("/updatebalance", (req, res) => {
const { email, user_balance } = req.body;
User.findOneAndUpdate(
{ email },
{ $inc: { user_balance: user_balance } },
function (err, result) {
if (err) {
res.send(err);
} else {
res.send(result);
}
}
);
});

还有auth的来源:

这是auth-reducer:https://pastebin.com/upHdvtiF

以下是操作:https://pastebin.com/Ajp7S1Yi

这就是终点:https://pastebin.com/NwCHCitY

我得到了一个登录和注册页面,一旦用户注册,就会创建auth。在操作链接中,您可以看到登录和注册操作。

我认为您必须添加用户层

const initalState = {
user: {
email: null,
user_balance: null,
}
};

和还原剂

export default function (state = initialState, action) {
switch (action.type) {
case UPDATE_BALANCE_SUCCESS:
return {
...state,
user: {
...state.user,
email: action.payload.email,
user_balance: action.payload.user_balance,
}
};
}
}

相关内容

  • 没有找到相关文章

最新更新