首页 文章

从反应路由器v4中的redux动作重定向

提问于
浏览
8

我在我的应用程序中使用 react-router v4 进行路由 . 在主页上,有一个表格 . 当用户填写表单并点击提交按钮时,将调度该操作(showResultofCar)并将其重定向到主页中不是子项的结果页面,而不是从上到下具有不同UI的不同页面 .

我尝试这样做,但只是路由已经过渡但没有调度动作但显示相同的主页而不是新页面(结果)

index.js

ReactDOM.render(
  <Provider store={createStoreWithMiddleware(reducers)}>
    <ConnectedIntlProvider>
      <Router>
        <App />
      </Router>
    </ConnectedIntlProvider>
  </Provider>
  , document.querySelector('.app'));

app.js

render() {
  return (
      <div className="container-fluid">
        <Nav
          showModal={(e) => this.showModal(e)}
          hideModal={() => this.hideModal()}
          show={this.state.show}
          onHide={() => this.hideModal()}
        />
          <Banner />
          <Media />
          <Footer />
        </div>
        );
}

form.js(it is a child component of banner which is a child component of app)

onSubmit = (e) => {
  e.preventDefault();
  const originwithCountry = e.target.Origen.value;
  const originwithCity = originwithCountry.split(', ')[0];
  const cityFrom = base64.encode(originwithCity);
  const startDate = (new Date(e.target.startDate.value).getTime() / 1000);
  this.props.showResultofCar(cityFrom, cityTo, startDate);
  this.context.router.transitionTo('/result');
  }

render() {
  const { focusedInput } = this.state;
  const { intl } = this.props;
  return (
    <div className="form-box text-center">
      <div className="container">
        <form className="form-inline" onSubmit={this.onSubmit}>
          <div className="form-group">
            <Field
              name='Origen'
              component={renderGeoSuggestField}
            />
          </div>
          <div className="form-group">
            <Field
              name="daterange"
              onFocusChange={this.onFocusChange}
            />
          </div>
          <Link to="/result">
          <button type="submit" className="btn btn-default buscar">
            { intl.formatMessage({ id: 'buscar.text' })}
          </button>
        </Link>
        </form>
      </div>
    </div>
  );
}

result-parent.js

class ResultParent extends Component {
  render() {
    return (
      <div className="result-page">
        <Match pattern='/result' component={Result} />
      </div>
    );
  }
}

result.js

class Result extends Component {
render() {
  return (
    <div className="result-page">
      <ResultNav />
      <Filtering />
      <Results />
    </div>
  );
}
}

actions/index.js

export function showResultofCar(cityFrom, cityTo, date) {
  return (dispatch) => {
    dispatch({ type: 'CAR_FETCH_START' });
    const token = localStorage.getItem('token');
    console.log('date', date);
    return axios.get(`${API_URL}/car/{"cityFrom":"${cityFrom}","cityTo":"${cityTo}","date":${date}}.json/null/${token}`)
      .then((response) => {
        console.log('response is', response);
        dispatch({ type: 'CAR_FETCH_SUCCESS', payload: response.data });
      })
      .catch((err) => {
        dispatch({ type: 'CAR_FETCH_FAILURE', payload: err });
      });
  };
}

我的方式不起作用 . 我现在如何使用反应路由器v4重定向内部动作?

此外,我不希望结果显示在App组件(父级)中,因为结果页面将与其自己的导航栏,过滤和结果选项完全不同 .

Note: React router v4 has been used

1 回答

  • 2

    您可以做的是在 App.js 中创建一个重定向处理程序:

    constructor(props) {
      super(props);
      this.handleRedirect = this.handleRedirect.bind(this);
      this.handleSubmitForm = this.handleSubmitForm.bind(this);
    }
    
    handleRedirect() {
      this.props.push('/result');
    }
    
    handleSubmitForm(cityFrom, cityTo, startDate) {
      this.props.showResultofCar(cityFrom, cityTo, startDate, this.handleRedirect);
    }
    ...
    

    并通过道具为您的表单组件提供 handleSubmitForm . 这样,您就不必将Form组件连接到Redux调度操作 .

    在您的 showResultofCar 操作中,您现在可以在Promise上成功调用此重定向处理程序:

    export function showResultofCar(cityFrom, cityTo, date, redirectOnSuccess) {
      ...
        .then((response) => {
          // console.log('response is', response);
          dispatch({ type: 'CAR_FETCH_SUCCESS', payload: response.data });
          redirectOnSuccess();
        })
      ...
    }
    

    我知道这可能不是最干净的方式,但它会为你做的工作 .

相关问题