首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在React路由器Dom v6中推入历史

如何在React路由器Dom v6中推入历史
EN

Stack Overflow用户
提问于 2022-03-14 09:53:14
回答 3查看 4.8K关注 0票数 7

我尝试了很多次,但是无法升级我的代码以使push.history正常工作。

下面是我使用react router v5的旧代码:

这段代码在以前的版本中运行得很好,但是当我升级到v6时,我不知道新版本中的withRouterpush.history将被什么取代。

代码语言:javascript
复制
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 ) )

我的行动文件

代码语言:javascript
复制
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
    })
  })
}
EN

回答 3

Stack Overflow用户

发布于 2022-05-18 07:45:11

react-router-dom 6版本之后,push.history已经改变了。

Push.history('/dashboard') -> navigate('/dashboard')

使用usenavigate钩子的示例:

代码语言:javascript
复制
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>
  );
} 
票数 4
EN

Stack Overflow用户

发布于 2022-07-18 02:15:19

useNavigate在react路由器v6中的使用

代码语言:javascript
复制
import {useNavigate} from 'react-router-dom';
const navigate = useNavigate();
navigate('/home')
票数 1
EN

Stack Overflow用户

发布于 2022-07-18 03:30:24

useNavigate钩子返回一个函数,该函数允许您以编程方式导航,例如在提交表单之后。如果使用replace: true,导航将替换历史堆栈中的当前条目,而不是添加新条目。

导航函数有两个签名:

  • 通过可选的第二个{ replace, state } arg传递一个To值(与<Link to>相同的类型),或者
  • 传递您想要进入历史堆栈的增量。例如,navigate(-1)相当于按后退按钮。

您可以遵循以下示例:

代码语言:javascript
复制
import { useNavigate } from "react-router-dom";

function exampleNavigation() {
  let navigate = useNavigate();
  navigate('/your_url');
} 
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71465787

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档