gpt4 book ai didi

javascript - 发出发布请求时状态未正确更新

转载 作者:行者123 更新时间:2023-11-28 03:22:36 26 4
gpt4 key购买 nike

嘿,我不知道为什么我的状态没有在 DOM 中更新,我确信我缺少一些关键的 react 原理。 Heres the photo of what my DOM looks like after I submit a post

当我点击提交并填写信息时,显示的不是帖子,而是显示空白帖子。我必须手动重新加载页面才能显示添加的内容。我想我实际上正在解决一些同步问题,如果您看到任何问题,请告诉我我能做什么。

如果您想完整查看,我会将最相关的文件的代码放在下面,并在底部附加存储库。

dataActions.js

import { SET_POSTS, LOADING_DATA, DELETE_POST, POST_PRODUCT, SET_ERRORS, CLEAR_ERRORS, LOADING_UI } from "../types";
import axios from 'axios';
//GET ALL PRODUCTS
export const getPosts = () => dispatch => {
dispatch({ type: LOADING_DATA });
axios.get('/posts')
.then(res => {
dispatch({
type: SET_POSTS,
payload: res.data
})
})
.catch(err => {
dispatch({
type: SET_POSTS,
payload: []
})
})
}
//POST PRODUCT
export const postProduct = (newPost) => (dispatch) => {
dispatch({ type: LOADING_UI });
axios.post('/post', newPost)
.then(res => {
dispatch({
type: POST_PRODUCT,
payload: res.data
})
console.log("success");
dispatch({ type: CLEAR_ERRORS })
})
.catch(err => {
dispatch({
type: SET_ERRORS,
payload: err.response.data
})
})
}
//DELETE PRODUCT
export const deletePost = (postId) => (dispatch) => {
axios.delete(`/post/${postId}`)
.then(() => {
dispatch({ type: DELETE_POST, payload: postId })
})
.catch(err => console.log(err))
}

dataReducer.js

import { SET_POSTS } from '../types';
import { LOADING_DATA, DELETE_POST, POST_PRODUCT/*, SET_POST*/ } from '../types';

const initialState = {
posts: [],
post: {},
loading: false
};

export default function(state = initialState, action){
switch(action.type){
case LOADING_DATA:
return {
...state,
loading: true
}
case SET_POSTS:
return{
...state,
posts: action.payload,
loading: false
}
case DELETE_POST:
let index = state.posts.findIndex(post => post.postId === action.payload);
state.posts.splice(index, 1);
return {
...state
}
case POST_PRODUCT:
return {
...state,
posts: [action.payload, ...state.posts]
}
default:
return state
}
}

PostProduct.js

import React, { Component, Fragment } from "react";
import { withStyles } from "@material-ui/core/styles";
import PropTypes from "prop-types";
import MyButton from "../util/MyButton";

//MUI Stuff
import Button from "@material-ui/core/Button";
import TextField from "@material-ui/core/TextField";
import Dialog from "@material-ui/core/Dialog";
import DialogTitle from "@material-ui/core/DialogTitle";
import DialogContent from "@material-ui/core/DialogContent";
import DeleteOutline from "@material-ui/icons/DeleteOutline";
import CircularProgress from '@material-ui/core/CircularProgress';
import AddIcon from '@material-ui/icons/Add';
import CloseIcon from "@material-ui/icons/Close";
//REDUX
import { connect } from "react-redux";
import { postProduct } from "../redux/actions/dataActions";

const styles = {
form: {
textAlign: "center"
},
image: {
margin: "20px auto 20px auto",
width: "50px"
},
pageTitle: {
margin: "10px auto 10px auto"
},
textField: {
margin: "10px auto 10px auto"
},
button: {
marginTop: 20,
postition: "relative"
},
customError: {
color: "red",
fontSixe: "0.8rem",
marginTop: 10
},
progress: {
position: "absolute"
},
submitButton: {
position: "relative"
},
progressSpinner: {
position: 'absolute'
},
closeButton: {
position: 'absolute',
left: '90%',
top: '10%'
}
};

class PostProduct extends Component {
state = {
open: false,
name: '',
errors: {}
};
UNSAFE_componentWillReceiveProps(nextProps){
if (nextProps.UI.errors) {
this.setState({
errors: nextProps.UI.errors
})
}
}
handleOpen = () => {
this.setState({ open: true })
}
handleClose = () => {
this.setState({ open: false })
}
handleChange = (event) => {
this.setState({ [event.target.name]: event.target.value })
}
handleSubmit = (event) => {
event.preventDefault();
this.props.postProduct({ body: this.state.body })
}
render(){
const { errors } = this.state;
const { classes, UI: {loading }} = this.props;
return (
<Fragment>
<MyButton onClick={this.handleOpen} tip="Post a Product">
<AddIcon />
</MyButton>
<Dialog
open={this.state.open}
onClose={this.handleClose}
fullWidth
maxWidth="sm"
>
<MyButton
tip="close"
onClick={this.handleClose}
tipClassName={classes.closeButton}
>
<CloseIcon />
</MyButton>
<DialogTitle>Post the new Product</DialogTitle>
<DialogContent>
<form onSubmit={this.handleSubmit}>
<TextField
name="name"
type="text"
lable="Post Product"
multiline
rows="3"
placeholder="name"
error={errors.body ? true : false}
helperText={errors.body}
className={classes.textFields}
onChange={this.handleChange}
fullWidth
/>
<TextField
name="images"
type="text"
lable="image"
multiline
rows="3"
placeholder="image"
error={errors.body ? true : false}
helperText={errors.body}
className={classes.textFields}
onChange={this.handleChange}
fullWidth
/>
<TextField
name="itemCategory"
type="text"
lable="Painting"
multiline
rows="3"
placeholder="Painting"
error={errors.body ? true : false}
helperText={errors.body}
className={classes.textFields}
onChange={this.handleChange}
fullWidth
/>
<TextField
name="link"
type="text"
lable="link"
multiline
rows="3"
placeholder="https://etsy.com"
error={errors.body ? true : false}
helperText={errors.body}
className={classes.textFields}
onChange={this.handleChange}
fullWidth
/>
<TextField
name="info"
type="text"
lable="blah blah blah"
multiline
rows="3"
placeholder="info"
error={errors.body ? true : false}
helperText={errors.body}
className={classes.textFields}
onChange={this.handleChange}
fullWidth
/>
<TextField
name="price"
type="text"
lable="Price"
multiline
rows="3"
placeholder="75.99"
error={errors.body ? true : false}
helperText={errors.body}
className={classes.textFields}
onChange={this.handleChange}
fullWidth
/>
<TextField
name="available"
type="text"
lable="available?"
multiline
rows="3"
placeholder="true"
error={errors.body ? true : false}
helperText={errors.body}
className={classes.textFields}
onChange={this.handleChange}
fullWidth
/>
<TextField
name="highEnd"
type="text"
lable="High-end or not?"
multiline
rows="3"
placeholder="false"
error={errors.body ? true : false}
helperText={errors.body}
className={classes.textFields}
onChange={this.handleChange}
fullWidth
/>
<Button
type="submit"
variant="contained"
color="primary"
className={classes.submitButton}
disabled={loading}
>
Submit
{loading && (
<CircularProgress
size={30}
className={classes.progressSpinner}
/>
)}
</Button>
</form>
</DialogContent>
</Dialog>
</Fragment>
);
}


} // END CLASS

PostProduct.propTypes = {
postProduct: PropTypes.func.isRequired,
UI: PropTypes.object.isRequired
}

const mapStateToProps = (state) => ({
UI: state.UI
})

export default connect(mapStateToProps, { postProduct })(withStyles(styles)(PostProduct))

前端代码位于此存储库中:https://github.com/jIrwinCline/planum-front

感谢您的帮助。我知道这是一个大问题......

最佳答案

如果成功,发布产品thunk会设置LOADING_UI,然后设置POST_PRODUCT

export const postProduct = (newPost) => (dispatch) => {
dispatch({ type: LOADING_UI });
axios.post('/post', newPost)
.then(res => {
dispatch({
type: POST_PRODUCT,
payload: res.data
})
console.log("success");
dispatch({ type: CLEAR_ERRORS })
})
.catch(err => {
dispatch({
type: SET_ERRORS,
payload: err.response.data
})
})

在您的 reducer 中,没有 LOADING_UI 情况,POST_PRODUCT 情况仅设置发布数据,但不会关闭加载:

case POST_PRODUCT:
return {
...state,
posts: [action.payload, ...state.posts]
}

我怀疑您必须向您的reducer添加一个LOADING_UI案例,并确保POST_PRODUCT在使用新帖子更新您的商店时将loading设置为false。

关于javascript - 发出发布请求时状态未正确更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58985962/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com