【问题标题】:Push function dont work inside Action推送功能在 Action 中不起作用
【发布时间】:2017-10-11 17:40:03
【问题描述】:

我的组件和操作没有什么问题。 在我的组件中,我通过(登录名,密码)进行授权。然后在行动创建者中,我向我的服务器发出发布请求,当状态为 200 并希望将用户推送到其他路径时,例如“/”,但这不起作用。

import React, { Component } from 'react';
import { Field, reduxForm } from 'redux-form';
import * as actions from '../../actions';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';

class Signin extends Component{

constructor(props){
super(props);
this.state= {};
this.onSubmit = this.onSubmit.bind(this);
}

renderField(field){
    return(
    <div className="form-group">
        <label>{field.label}</label>
        <input
            className="form-control"
            type="text"
            {...field.input}
            />

    </div>
    );
}

onSubmit(e){
    e.preventDefault();
    let {username,password} = this.state;
    this.props.actions.signinUser({username,password});
    this.setState({
        username: '',
        password: ''
    })
}




render(){
    let {username,password} = this.state;


    return(
        <form onSubmit={this.onSubmit}>

            <Field
                label="Username:"
                name="username"
                component={this.renderField}
                onChange={e => this.setState({username: e.target.value})}
            />
            <Field
                label="Password:"
                name="password"
                component={this.renderField}
                onChange={e => this.setState({password: e.target.value})}
            />
            <button action="submit" className="btn btn-primary"> Sign In 
</button>
        </form>

    );
 }
}


function mapStateToProps(state) {
return { form: state.form };
}

const mapDispatchToProps = (dispatch)=> {
return {
    actions : bindActionCreators(actions , dispatch)
};
}

Signin = connect(
mapStateToProps,
mapDispatchToProps 
)(Signin);

export default reduxForm({
form: 'signin'
})(Signin);

import axios from 'axios';



export function signinUser({username,password}){
return function(dispatch){

    axios.post('http://localhost:8585/auth', { username, password})
    .then(response => {

          this.context.history.push('/'); or history.push('/'); 
            also tried  `this.props.history`?

        localStorage.setItem('token', response.data.token);
        console.log("ok");

      })
      .catch(() => {
        console.log("not ok");
      });
    };

}

class App extends Component {
 render() {
return (
  <Router>
      <div className="container">
      <Header />
      <Route exact path="/" component={Home} />
      <Route path="/signin" component={SignIn} />
      <Route path="/about" component={About} />
    </div>
  </Router>
 );
 }
}

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore,applyMiddleware } from 'redux';

import './index.css';
import App from './components/App';
import registerServiceWorker from './registerServiceWorker';
import reducers from './reducers';
import reduxThunk from 'redux-thunk'

const createStoreWithMiddleware = applyMiddleware(reduxThunk)(createStore);


ReactDOM.render(
<Provider store={createStoreWithMiddleware(reducers)}>
<App />
</Provider>

, document.getElementById('root'));
registerServiceWorker();

有什么想法吗?我使用反应路由器 v4。

我尝试了很多东西,(创建自己的历史),将道具中的功能从组件传递到动作。还是不行..

【问题讨论】:

  • 你在哪里写history.push()??
  • 对不起,我编辑帖子。我尝试在 localstorage.setkey 之后推送
  • 我不这么认为,您可以在 axios api 调用中使用历史对象。这也不是一种可取的方式。相反,您可以在componentWillRecieveProps 中进行操作。您可以检查localStorage 中的令牌是否存在,只需使用this.props.history.push() 从那里重定向即可。您可以通过以下任何一种方式在 react-router 4 中重定向。stackoverflow.com/questions/42123261/…
  • @NarasimhaReddy 这是这样做的好方法吗?在 localStorage 中检查密钥,如果有密钥,我将用户推送到 / ?

标签: reactjs react-router react-redux


【解决方案1】:

你必须把所有的东西都放在BrowserRouter中。检查下面的代码。

  <Provider store={configureStore()}>
    <BrowserRouter>
        <LocaleProvider locale={enUS}>
            <Route path='/' component={App} />
        </LocaleProvider>
    </BrowserRouter>
</Provider>

您将通过 this.props.history.push('you_path'); 获取历史记录并使用 push() p>

检查React Router Documentation。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-14
    • 1970-01-01
    • 2020-09-13
    • 2019-02-04
    • 1970-01-01
    • 2023-03-31
    • 2023-03-09
    • 1970-01-01
    相关资源
    最近更新 更多