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



在嵌套了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);

在reducer中,您应该返回一个更新的reducer对象。在ADD_BOOK中添加新属性eventDetails。你在什么地方用它吗?你的新减速器看起来是:{books:[初始图书列表],eventDetails:[初始书籍列表和新书]}。当您在ADD_BOOK中将eventDetails更改为图书时,您的图书列表将在没有其他请求的情况下更新。

最新更新