React / Redux:GET axios调用导致无限循环,onSubmit方法不会对用户产生视觉输出

时间:2018-12-06 13:08:57

标签: reactjs redux axios

在嵌套了addBook动作的表单中单击提交按钮之后,数据将传递到DB,但不会立即输出到屏幕(我必须每次刷新页面才能从DB输出新添加的数据)。

我试图将getBooks函数放入componentDidUpdate()生命周期挂钩中,但这会导致无限循环。

getBooks操作

export const getBooks = () => dispatch => {
 axios.get('https://damianlibrary.herokuapp.com/library')
  .then(res => dispatch({
    type: GET_BOOKS,
    payload: res.data
  }))
};

addBook操作

export const addBook = book => dispatch => {
 axios.post('https://damianlibrary.herokuapp.com/library', book)
  .then(res => dispatch({
   type: ADD_BOOK,
   payload: res.data
  }))
};

bookReducer

const initialState = {
 books: []
}

export default function(state = initialState, action) {
 switch(action.type) {
  case GET_BOOKS:
   return {
    ...state,
    books: action.payload
   };
  case DELETE_BOOK:
   return {
    ...state,
    books: state.books.filter(book => book.book_id !== action.payload)
   };
  case ADD_BOOK:
   return {
    ...state,
    eventDetails: [action.payload, ...state.books]
   };
  default:
   return state;
 }
}

Form.js组件

import React, { Component } from 'react';

import { connect } from 'react-redux';
import { addBook, getBooks } from '../../actions/bookActions';

import './Form.css';

class Form extends Component {

state = {
 name: '',
 author: '',
 isbn: ''
}

componentDidMount () {
 this.props.getBooks();
}

onChangeHandler = (e) => {
 this.setState({ [e.target.name]: e.target.value })
};

onSubmitHandler = (e) => {

 const {name, author, isbn} = this.state

      const newBook = {
      name: name,
      author: author,
      isbn: isbn
    }
    this.props.addBook(newBook);

    this.setState({
      name: '',
      author: '',
      isbn: ''
    })
  e.preventDefault();
}

render() {
 const { name, author, isbn } = this.state;

 return (
  <div className='formContainer'>
    <div className='form'>
      <form className='bookForm' onSubmit={this.onSubmitHandler.bind(this)}>
        <div className='inputs'>
          <input 
          type='text' 
          name='name'  
          placeholder='Book name'
          onChange={this.onChangeHandler}
          value={name}/>
          <input 
          type='text' 
          name='author'  
          placeholder='Book author'
          onChange={this.onChangeHandler}
          value={author}/>
          <input 
          type='text' 
          name='isbn'  
          placeholder='ISBN'
          onChange={this.onChangeHandler}
          value={isbn}/>
        </div>
        <div className='buttonSpace'>
          <button>Add book</button>
        </div>
      </form>
    </div>
  </div>
  )
 }

}

const mapStateToProps = (state) => ({
 book: state.book
});

export default connect(mapStateToProps, { addBook, getBooks })(Form);

1 个答案:

答案 0 :(得分:1)

在化简器中,您应该返回更新的化简器对象。在ADD_BOOK中,添加新属性eventDetails。你在某处使用它吗? 您的新减速器外观为:{书籍:[初始书籍清单],eventDetails:[初始书籍清单和新书籍]}。当您将eventDetails更改为ADD_BOOK中的图书时,您的图书清单将更新,而无需其他请求。