状态未更新

时间:2020-10-18 18:27:07

标签: reactjs

当我更改帖子并单击“编辑帖子”按钮时,将被带到显示该帖子的页面。但是我对帖子所做的更改不可见。我在做什么错了?

我正在使用上下文API进行状态管理。用于编辑帖子的状态更改逻辑位于操作功能类型为“ postEdited”的reducer函数内部。

import React, { useState, useContext } from "react";
import { useHistory, useParams } from "react-router-dom";
import { postsContext } from "../../Context";

const EditPost = () => {
  const { id } = useParams();
  const postIdNum = parseInt(id);

  const history = useHistory();

  const data = useContext(postsContext);

  const postClicked = data.posts.find((post) => post.id === postIdNum);
  let postClickedTitle;
  let postClickedBody;
  if (postClicked) {
    postClickedTitle = postClicked.title;
    postClickedBody = postClicked.body;
  }

  const [title, setTitle] = useState(postClickedTitle);
  const [body, setBody] = useState(postClickedBody);

  const onTitleChanged = (e) => setTitle(e.target.value);
  const onContentChanged = (e) => setBody(e.target.value);

  const onEditPostClicked = (e) => {
    e.preventDefault();

    const editedPost = {
      id,
      title,
      body,
    };

    if (title && body) {
      data.dispatch({
        type: "editedPost",
        payload: editedPost,
      });
      history.push(`/posts/${postIdNum}`);
    }
  };

  return (
    <section>
      <form onSubmit={onEditPostClicked}>
        <div className="form-group">
          <label htmlFor="postTitle">Title:</label>
          <input
            type="text"
            id="postTitle"
            name="postTitle"
            value={title}
            onChange={onTitleChanged}
          />
        </div>
        <div className="form-group">
          <label htmlFor="postContent">Body:</label>
          <input
            type="text"
            id="postContent"
            name="postContent"
            value={body}
            onChange={onContentChanged}
          />
        </div>
        <button className="btn btn-primary">Edit Post</button>
      </form>
    </section>
  );
};

export default EditPost;
import React, { Component } from "react";
import axios from "axios";

export const postsContext = React.createContext();

const reducer = (state, action) => {
  switch (action.type) {
    case "postAdded":
      return {
        ...state,
        posts: [action.payload, ...state.posts],
      };
    case "postEdited":
      return {
        ...state,
        posts: state.posts.map((post) =>
          post.id === action.payload.id ? (post = action.payload) : post
        ),
      };
    default:
      return state;
  }
};

export class Provider extends Component {
  state = {
    posts: [],
    dispatch: (action) => this.setState((state) => reducer(state, action)),
  };

  async componentDidMount() {
    const response = await axios.get(
      "https://jsonplaceholder.typicode.com/posts"
    );
    const posts = response.data.slice(0, 50);
    this.setState({ posts });
  }

  render() {
    return (
      <postsContext.Provider value={this.state}>
        {this.props.children}
      </postsContext.Provider>
    );
  }
}

export const Consumer = postsContext.Consumer;

0 个答案:

没有答案