【问题标题】:How to redirect to a another page in reactjs when switch case statement is executed?执行switch case语句时如何重定向到reactjs中的另一个页面?
【发布时间】:2020-08-29 10:53:40
【问题描述】:

我想知道如何在 case 语句之后进行重定向。我一直在制作这段代码,但是在 case 语句之后,什么也没有发生。我在网上查看,但似乎没有任何效果。当我提交经过验证的表单时,它不会重定向或刷新。

代码

import { Redirect } from 'react-router-dom'
import React, { Component } from 'react'

const initState = {}

const adReducer = (state = initState, action) => {
  switch (action.type) {
    case 'CREATE_AD_SUCCESS':
    alert('create ad success');
    return <Redirect to='/' /> ;
  case 'CREATE_AD_ERROR':
    alert('create ad error');
    return state;
  default:
    return state;
  }
 };

export default adReducer;

adAction.js 代码

export const createAd = (ad) => {
  return (dispatch, getState, {getFirebase,getFirestore}) => {
  // make async call to database
  const firestore = getFirestore();
  const profile = getState().firebase.profile;
  const authorId = getState().firebase.auth.uid;
  firestore.collection('ads').add({
  ...ad,
  authorFirstName: profile.firstName,
  authorLastName: profile.lastName,
  authorId: authorId,
  createdAt: new Date()
  }).then(() => {
    dispatch({ type: 'CREATE_AD_SUCCESS' });
  }).catch(err => {
    dispatch({ type: 'CREATE_AD_ERROR' }, err);
  });
 }
};

创建广告代码:

import React, { Component } from 'react'
import { connect } from 'react-redux'
import { createAd } from '../../store/actions/adActions'
import { Redirect } from 'react-router-dom'
import firebase from "firebase";
import FileUploader from "react-firebase-file-uploader";

class CreateAd extends Component {
  state = {
    title: '',
    content: '',
    avatar: "",
    isUploading: false,
    progress: 0,
    avatarURL: "",
    contactno:""
  }
  handleChange = (e) => {
    this.setState({
      [e.target.id]: e.target.value
    })
  }
  handleSubmit = (e) => {
    e.preventDefault();
    this.props.createAd(this.state);
  }

handleUploadStart = () => this.setState({ isUploading: true, progress: 0 });
handleProgress = progress => this.setState({ progress });
handleUploadError = error => {
  this.setState({ isUploading: false });
  console.error(error);
};

handleUploadSuccess = filename => {
  this.setState({ avatar: filename, progress: 100, isUploading: false });
  firebase
    .storage()
    .ref("images")
    .child(filename)
    .getDownloadURL()
    .then(url => this.setState({ avatarURL: url }));
};

  render() {
    const { auth } = this.props;
    if (!auth.uid) return <Redirect to='/signin' /> 
    return (
      <div className="container">
        <form className="white" onSubmit={this.handleSubmit}>
          <h5 className="grey-text text-darken-3">Create a New Ad</h5>
          <div className="input-field">
            <input type="text" id='title' onChange={this.handleChange} />
            <label htmlFor="title">Ad Title</label>
          </div>
          <div className="input-field">
            <textarea id="content" className="materialize-textarea" onChange={this.handleChange}></textarea>
            <label htmlFor="content">AdContent</label>
          </div>
          <div className="input-field">
            <input type="text" id='contactno' onChange={this.handleChange} />
            <label htmlFor="title">Contact Number</label>
          </div>


          { this.state.progress==100? <div class="col-md-4">
          <img class="responsive-img" src={this.state.avatarURL}></img>
          </div>:""}
          <br/>
          <label style={{backgroundColor: 'steelblue', color: 'white', padding: 10, borderRadius: 4, pointer: 'cursor'}}>
            Upload a photo

          {/* {this.state.isUploading && <p>Progress: {this.state.progress}</p>}
          {this.state.avatarURL && <img src={this.state.avatarURL} />} */}
            <FileUploader
              hidden
              accept="image/*"
              storageRef={firebase.storage().ref('images')}
              onUploadStart={this.handleUploadStart}
              onUploadError={this.handleUploadError}
              onUploadSuccess={this.handleUploadSuccess}
              onProgress={this.handleProgress}
            />
            </label>



          <div className="input-field">
            <button className="btn pink lighten-1">Create</button>
          </div>
        </form>
      </div>
    )
  }
}

const mapStateToProps = (state) => {
  return {
    auth: state.firebase.auth
  }
}

const mapDispatchToProps = dispatch => {
  return {
    createAd: (ad) => dispatch(createAd(ad))
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(CreateAd)

这些是我的代码。

【问题讨论】:

  • 你如何使用adReducer
  • @SMAKSS 你想知道什么?
  • 这很明显。 adReducer如何使用?在其他组件中如何调用和传递参数?
  • @SMAKSS 上面我添加了 adAction.js 代码。

标签: reactjs redirect react-router-dom


【解决方案1】:

您应该使用return window.location.replace("/") 而不是return &lt;Redirect to="/" /&gt;

“React Router Redirect”从 A 重定向到 B,例如 &lt;Redirect from="/about" to="/" /&gt;

【讨论】:

  • 它正在工作。但是当我使用它时,它会显示创建广告成功和创建广告错误警报。你知道为什么会这样吗?
  • 我相信它会调用您的操作 createAd 两次。重定向之前和之后的一个。你有源代码,我可以看看并帮助你更深入地解决这个问题吗?
  • @F Pavanela 我也在问题中添加了 createAd 代码。请参考
猜你喜欢
  • 2018-10-24
  • 1970-01-01
  • 2015-07-16
  • 1970-01-01
  • 2019-03-31
  • 2020-06-15
  • 2022-01-19
  • 2014-03-27
  • 2022-01-04
相关资源
最近更新 更多