1

Использую axios для ajax запроса, само приложение на react и redux, мне нужно, чтобы при запросах страница не перезагружалась. При get запросе все ок, а вот при post все перерендеривается.

const Main = connect(mapStateToProps, mapDispatchToProps)(
   class extends React.Component {
    componentDidMount() {
      getEmployeesList()

    }
    constructor(props){
      super(props)
      this.state = {flag: false}
    }
    getForm() {
    this.setState({flag: true});
    const { createEmployee } = this.props.appAction;
    let request = employee;
    createEmployee(request);
    }
    closeForm() {
    this.setState({flag: false});
    console.log('flag: ', this.state.flag)
  }
    render() {
        let st = this.props.employees
        console.log("It is props: ", st);
        let add = '';
        (this.state.flag == true)?(add = <EmployeesCreator closeForm={this.closeForm.bind(this)}/>):(add = '');
        return <div>
        <button onClick={this.getForm.bind(this)}>Add</button>
        <EmployeesList employees={st}/> 
        {add} 
        </div>

      }
  });

function mapStateToProps(state) {
  return {
    employees: state.employees,
    //newEmployee: state.newEmployee,

  }
}

function mapDispatchToProps(dispatch) {
    return {
        appAction: bindActionCreators(appAction, dispatch)
    }
}
/***********************************************************/
export function createEmployee(employee){

     var url = 'http://localhost:3000/newEmployee';
     var request = employee;
     return (dispatch) => {
         dispatch({
             type: AJAX_REQUEST,
             newEmployee: {}
         })
         axios.post(url, request)
             .then(result => {
                 dispatch({
                     type: AJAX_SUCCESS,
                     newEmployee: {
                         result: result.data,
                     }
                 })
             })
             .catch(error => {
                 dispatch({
                     type: AJAX_ERROR,
                     newEmployee: {},
                     errors: error
                 })
             })
     }


  }
/****************************************************************************/
export  function reducer(state, action) {
    switch(action.type) {
        case GET_EMPLOYEES_LIST:
            return {...state, employees: action.employees};
        case AJAX_SUCCESS:
            return {...state, newEmployee: action.newEmployee.result};
        default:
            return state;
    }
}

1 ответ 1

0
  1. Обрабатывай отправку формы, а не click
  2. Делай event.preventDefault() в обработчике

class App extends React.Component {
  render() {
    return (
      <form onSubmit={this.onSubmit}>
        <input type="text" ref={inp => this.inp = inp} />
        {" "}
        <input type="submit" value="Send" />
      </form>
    )
  }
  
  onSubmit = event => {
    event.preventDefault() // Без этого страница перезагрузится
    console.log(this.inp.value)
  }
}

ReactDOM.render(<App />, document.querySelector('main'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<main></main>

3
  • Сделал так, но все равно перезагрузка после post осталась
    – Nikita21
    13 дек 2017 в 20:35
  • @Nikita21, значит сделал как-то не так...
    – Qwertiy
    13 дек 2017 в 20:37
  • onSubmit = event => { event.preventDefault(); axios.post('localhost:3000/newEmployee', this.inp.value) } render() { return <form onSubmit={this.onSubmit}> <input type="text" ref={inp => this.inp = inp} /> <input type="submit" value="Добавить" /> </form> }
    – Nikita21
    13 дек 2017 в 20:42

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.