保存帖子后如何更新网址

时间:2020-04-06 09:01:40

标签: javascript reactjs redux react-redux

我正在构建一个可以保存和更新帖子的编辑器。我面临的问题是,第一次保存帖子后,我从服务器获取了一个snippetId,我想立即在url中显示它,否则我的路线仍然是http://localhost:8000/editor,如果我点击了保存按钮再一次,它将保存具有不同ID的重复副本。第一次保存后,我希望编辑器URL为http://localhost:8000/editor/123之类,以便当我再次单击保存按钮时,它会更新帖子,而不是保存具有不同ID的重复副本。我想知道如何解决这个问题?有人可以帮我找到解决这个问题的方法

codesandbox

editor.js

import React, { Component } from "react";
import { connect } from "react-redux";
import { savePost, retrievePost } from "./actions/posts";

class Editor extends Component {
  constructor(props) {
    super(props);

    this.state = {
      title: "",
      enteredText: ""
    };
    this.commonChange = this.commonChange.bind(this);
  }
  commonChange(event) {
    this.setState({
      [event.target.name]: event.target.value
    });
  }
  componentDidMount() {
    //Load the snippet
    retrievePost(this.props.match.params.snippetId);
  }

  // Save Snippet
  performSave = snippets => {
    console.log("save function clicked");
    const { enteredText, title } = this.state;
    this.props.savePost({
      snippetId: this.props.match.params.snippetId, //if the url doesn't change then this also doesn't change so I get duplicate copies 
      snippetDescription: enteredText,
      snippetTitle: title
    });
  };
  render() {
    return (
      <>
        <input
          type="text"
          id="titletext"
          placeholder="Enter title here"
          limit-to="64"
          className="inptxt"
          name="title"
          onChange={this.commonChange}
        />
        <button className="btn savebtn" onClick={this.performSave}>
          Save Snippet
          <i className="fas fa-save" />
        </button>

        <textarea name="enteredText" onChange={this.commonChange} />
      </>
    );
  }
}

const mapStateToProps = state => ({
  snippets: state.snippets
});

export default connect(
  mapStateToProps,
  { savePost, retrievePost }
)(Editor);

action.js

import { SAVE_POST, UPDATE_POST, RETRIEVE_POST, HOME_LOADED } from "./types";
import axios from "axios";
export const savePost = ({
  snippetId,
  snippetDescription,
  snippetTitle
}) => async dispatch => {
  const config = {
    headers: {
      "Content-Type": "application/json"
    }
  };

  let snippetData = {
    title: snippetTitle,
    snippetDescription: snippetDescription
  };
  // --------------------------------------
  console.log("in savePost action");
  try {
    if (snippetId == null) {
      const res = await axios.post("/api/savesnippets", snippetData, config);
      snippetData.snippetId = res.data; //cause I only get snippetId from the server
      dispatch({
        type: SAVE_POST,
        payload: snippetData
      });
    } else {
      //add snippetId here for update use only --------------------------------------
      await axios.post(
        "/api/update",
        JSON.stringify({ ...snippetData, snippetId }),
        config
      );
      // --------------------------------------
      dispatch({
        type: UPDATE_POST,
        payload: snippetData
      });
    }
  } catch (err) {
    console.log(err);
  }
};

1 个答案:

答案 0 :(得分:1)

您可以从react-router history.push()来实现此目的,例如:

history.push('/editor' + id_you_get_from_ajax_call);

并在获取ajax响应的地方使用它,因此,每次成功,您都会获得一个新的id_you_get_from_ajax_call,它将更新路由。

并为editor创建匹配的路由,例如:

<Route path="editor/:id" component={ YOUR_COMPONENT } />

React-router history.push() Reference