【发布时间】:2020-07-19 04:53:33
【问题描述】:
React 功能组件状态:
const [image, setImage] = useState("");
const [imageUrl, setImageUrl] = useState("");
这是我组件中的 useEffect:
useEffect(() => {
props.profile();
}, [props]);
您可以使用此input 上传个人资料图片。
<input
style={{ display: "none" }}
name="image"
id="image"
type="file"
accept=".jpg, .png, .jpeg"
value={""}
onChange={(e) => {
setImage(e.target.files[0]);
}}
/>
<label htmlFor="image">
<img src={user.user.image} alt="profile pic" />
</label>
更新配置文件 Redux 操作:
export const updateProfile = (updateProfile) => (dispatch) => {
const token = localStorage.getItem("token");
if (token) {
axios
.put("http://localhost:5000/updateProfile", updateProfile, {
headers: { "X-Auth-Token": token },
})
.then((res) => {
dispatch({
type: UPDATE_PROFILE,
payload: res.data,
});
});
}
};
这是在我的 React 功能组件中:
if (image) {
const uploadTask = storage.ref(`images/${image.name}`).put(image);
uploadTask.on(
"state_changed",
(snapshot) => {},
(error) => {
console.log(error);
},
() => {
storage
.ref("images")
.child(image.name)
.getDownloadURL()
.then((url) => {
setImageUrl(url);
})
.then(() => {
props.updateProfile({
image: imageUrl,
});
})
.then(() => {
setImage("");
setImageUrl("");
});
}
);
}
所以图片上传成功并改变状态并显示新图片,太好了。但是,它会触发 Redux 操作 4 次 (see here)。为什么?它应该只触发一次。
我根据用户从文件浏览器中选择图像来触发此功能。然后图像状态发生变化,因为有图像而条件运行,然后它应该按此顺序运行 firebase 函数和我的 redux 操作。是否可以按此顺序只触发一次?
编辑:
条件就在这个函数组件中的 return() 之上。
这是我的 props.profile()
export const profile = () => (dispatch) => {
dispatch({
type: FETCHING_PROFILE,
});
const token = localStorage.getItem("token");
if (token) {
axios
.get("http://localhost:5000/profile", {
headers: { "X-Auth-Token": token },
})
.then((res) =>
dispatch({
type: PROFILE,
payload: res.data,
})
);
}
};
【问题讨论】:
-
props.profile()是做什么的? -
另外,你的
if (image) {条件在你的反应函数组件中在哪里?它会在每次渲染时运行吗? -
@RobertCooper 我用更多细节编辑了我的问题。
标签: javascript reactjs firebase redux