javascript - 如何在 React Router Dom v6 中推送到历史记录

标签 javascript node.js reactjs redux react-hooks

我尝试了很多次,但无法升级我的代码以制作 push.history好好工作。
这是我使用 react-router-dom v5 的旧代码:
此代码在以前的版本中完美运行,但当我升级到 v6 时,我不知道 withRouter 的替换是什么和 push.history在新版本中。

import React from 'react'
import { withRouter } from 'react-router-dom'
import { connect } from 'react-redux'
import PropTypes from 'prop-types'
import TextFieldGroup from '../common/TextFieldGroup'
import TextAreaFieldGroup from '../common/TextAreaFieldGroup'
import SelectListGroup from '../common/SelectListGroup'
import InputGroup from '../common/InputGroup'
import { createProfile } from '../../actions/profileActions'

class CreateProfile extends React.Component{
    constructor( props ) {
        super(props)

        this.state = {
            displaySocialInputs: false,
            handle: '',
            company: '',
            website: '',
            location: '',
            status: '',
            skills: '',
            githubusername: '',
            bio: '',
            twitter: '',
            facebook: '',
            linkedin: '',
            youtube: '',
            instagram: '',
            errors:{}
        }


        this.onChange = this.onChange.bind(this)
        this.onSubmit = this.onSubmit.bind(this)

    }

    UNSAFE_componentWillReceiveProps( nextProps ) {
        if ( nextProps.errors ) {
            this.setState(()=>({ errors: nextProps.errors }))
        }
    }
    onSubmit( e ){
        e.preventDefault()
        
        const profileData = {
            handle: this.state.handle,
            company: this.state.company,
            website: this.state.website,
            location: this.state.location,
            status: this.state.status,
            skills: this.state.skills,
            githubusername: this.state.githubusername,
            bio: this.state.bio,
            twitter: this.state.twitter,
            facebook: this.state.facebook,
            linkedin: this.state.linkedin,
            youtube: this.state.youtube,
            instagram: this.state.instagram,
        }

        this.props.createProfile( profileData , this.props.history )
    }

    onChange( e ) {
        e.persist()
        this.setState(()=>({ [ e.target.name ]: e.target.value }))
    }

    render(){

        const options = [
            { label: 'وضعیت حرفه ای خود را انتخاب فرمایید *' , value : 0 },
            { label: 'برنامه نویس' , value : 'برنامه نویس' },
            { label: 'برنامه نویس مبتدی' , value : 'برنامه نویس مبتدی' },
            { label: 'برنامه نویس با تجربه' , value : 'برنامه نویس با تجربه' },
            { label: 'مدیر' , value : 'مدیر' },
            { label: 'درحال یادگیری' , value : 'درحال یادگیری' },
            { label: 'مدرس' , value : 'مدرس' },
            { label: 'دانشجو' , value : 'دانشجو' },
            { label: 'سایر' , value : 'سایر' }

        ]

        const { errors , displaySocialInputs } = this.state
        let socialInputes

        if ( displaySocialInputs ) {
            socialInputes = (
                    <div>
                        <InputGroup 
                            placeholder="آدرس شبکه توئیتر"
                            name="twitter"
                            icon="fab fa-twitter"
                            value={this.state.twitter}
                            onChange={this.onChange}
                            error={errors.twitter}
                        />


                        <InputGroup 
                            placeholder="آدرس شبکه فیسبوک"
                            name="facebook"
                            icon="fab fa-facebook"
                            value={this.state.facebook}
                            onChange={this.onChange}
                            error={errors.facebook}
                        />

                        <InputGroup 
                            placeholder="آدرس شبکه لینکدن"
                            name="linkedin"
                            icon="fab fa-linkedin"
                            value={this.state.linkedin}
                            onChange={this.onChange}
                            error={errors.linkedin}
                        />


                        <InputGroup 
                            placeholder="آدرس شبکه یوتیوب"
                            name="youtube"
                            icon="fab fa-youtube"
                            value={this.state.youtube}
                            onChange={this.onChange}
                            error={errors.youtube}
                        />


                        <InputGroup 
                            placeholder="آدرس شبکه اینستاگرم"
                            name="instagram"
                            icon="fab fa-instagram"
                            value={this.state.instagram}
                            onChange={this.onChange}
                            error={errors.instagram}
                        />

                    </div>
            )
        }

        return (
            <div className="create-profile">
                <div className="container">
                    <div className="row">
                        <div className="col-md-8 m-auto">
                            <h1 className="display-4 text-center">ساخت پروفایل شما</h1>
                            <p className="lead text-center">یک معرفی خوب وصعت کارتان را بیشتر می کند</p>
                            <small className="d-block bp-3 text-right">فیلدهای ستاره دار * اجباری می باشند</small>
                            <form onSubmit={ this.onSubmit }>

                                <TextFieldGroup 
                                    placeholder="هندلر پروفایل *"
                                    name="handle"
                                    value={this.state.handle}
                                    onChange={this.onChange}
                                    error={errors.handle}
                                    info="منظور از handle داشتن URL اختصاصی پروفایل شماست"
                                />


                                <SelectListGroup 
                                    placeholder="وضعیت"
                                    name="status"
                                    value={this.state.status}
                                    onChange={this.onChange}
                                    error={errors.status}
                                    options={options}
                                    info="تصویری از وضعیت کنونی شما"
                                />

                                <TextFieldGroup 
                                    placeholder="شرکت"
                                    name="company"
                                    value={this.state.company}
                                    onChange={this.onChange}
                                    error={errors.company}
                                    info="شرکت خودتان یا جایی که در آنجا مشغول به کار هستید"
                                />

                                <TextFieldGroup 
                                    placeholder="وب سایت"
                                    name="website"
                                    value={this.state.website}
                                    onChange={this.onChange}
                                    error={errors.website}
                                    info="وب سایت خودتان یا جاییکه کار می کنید"
                                />

                                <TextFieldGroup 
                                    placeholder="محل"
                                    name="location"
                                    value={this.state.location}
                                    onChange={this.onChange}
                                    error={errors.location}
                                    info="شهر یا استان و شهر"
                                />

                                <TextFieldGroup 
                                    placeholder="مهارت ها *"
                                    name="skills"
                                    value={this.state.skills}
                                    onChange={this.onChange}
                                    error={errors.skills}
                                    info="برای جدا سازی عبارت ها از کاما استفاده کنید html, css, js, php"
                                />


                                <TextFieldGroup 
                                    placeholder="نام کاربری شما در گیت هاب"
                                    name="githubusername"
                                    value={this.state.githubusername}
                                    onChange={this.onChange}
                                    error={errors.githubusername}
                                    info="برای ایجاد ارتباط و دسترسی به مخازن عمومی شما لطفا نام کاربری خودتان را وارد فرمایید"
                                />

                                <TextAreaFieldGroup 
                                    placeholder="مختصری از خودتان"
                                    name="bio"
                                    value={this.state.bio}
                                    onChange={this.onChange}
                                    error={errors.bio}
                                    info="لطفا توضیح مختصری از خودتان برای علاقمندان خودتان بنویسد"
                                />

                                <div className="mb-3 text-right">
                                    <button
                                        type="button"                                        
                                        className="btn btn-light" onClick={ () => {
                                        this.setState(( prevState)=>({ displaySocialInputs: !prevState.displaySocialInputs }))
                                    }}>
                                                اضافه کردن کانکشن در مدیا
                                    </button>
                                    <span className="text-muted">اختیاری میباشد</span>
                                </div>
                                        { socialInputes }
                                        <input type="submit" value="ثبت" className="btn btn-info btn-block mt-4" />
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        )
    }
}

CreateProfile.propTypes = {
    profile: PropTypes.object.isRequired,
    errors: PropTypes.object.isRequired
}

const mapStateToProps = ( state ) => {
    return {
        profile: state.profile,
        errors: state.errors
    }
}

export default connect( mapStateToProps , { createProfile })( withRouter( CreateProfile ) )

我的 Action 文件
export const createProfile = ( profileData , history ) => ( dispatch ) => {
  axios.post( '/api/profile' , profileData )
  .then(( result ) =>{
    history.push('/dashboard') 
  }).catch(( errors )=> {
    dispatch({
      type: GET_ERRORS,
      payload: errors.response.data
    })
  })
}

最佳答案

之后react-router-dom版本 6 push.history已经改变。Push.history('/dashboard') --> navigate('/dashboard')使用 usenavigate 的示例钩:

import { useNavigate } from "react-router-dom";

function Invoices() {
  let navigate = useNavigate();
  return (
    <div>
      <NewInvoiceForm
        onSubmit={async (event) => {
          let newInvoice = await createInvoice(
            event.target
          );
          navigate(`/invoices/${newInvoice.id}`);
        }}
      />
    </div>
  );
} 

关于javascript - 如何在 React Router Dom v6 中推送到历史记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71465787/

相关文章:

javascript - 确定哪些控件在 ASP.NET 网页上失败

javascript - Async/await vs then 哪个性能最好?

Javascript 图像预加载无法正常工作

node.js - 无法访问 Sails 服务上的 res 变量

javascript - 对JS对象中的解构元素进行操作

javascript - 为什么 JavaScript 中的正则表达式返回未定义?

javascript - 使用javascript将文档标题更改为从数据库记录

javascript - nodejs 从绝对路径运行脚本

javascript - componentDidMount() 中的 .map 中的 setState

reactjs - 在 preLoadedState 中发现意外的键,预计会找到已知的 reducer 键之一