我的useEffect函数不会在首次加载页面时触发redux动作调用,我只是得到一个错误,提示TypeError: Cannot read property 'length' of undefined
,可能是因为该动作从未触发,所以状态尚未加载。但是,当我重新加载页面时,它就可以正常工作,并且组件也可以毫无问题地加载。
这是我的react组件:
const BooksById = ({bookdetails:{bookDetails,loading},getBookById,match}) =>{
useEffect(()=>{
console.log("action fired")
getBookById(match.params.genre)
},[getBookById,match.params.genre])
const [modal, setModal] = useState(false);
const toggle = () => setModal(!modal);
const [formData, setFormData] = useState({
status: '',
rating: '',
review: ''
});
const {status, rating, review} = formData;
const onChange = e => setFormData({...formData, [e.target.name]:e.target.value})
const onSubmit = e => {
e.preventDefault();
console.log(status, rating, review);
};
return (
(
<Fragment>
{loading ? (
<Spinner />
) : (
<Fragment>
<Container style={{paddingTop: "1.5rem"}}>
<Card>
<Row>
<aside className="col-sm-3 border-right">
<article className="gallery-wrap">
<div className="img-wrap">
<center>
<Media src="https://via.placeholder.com/190x320"/>
</center>
</div>
<center>
<Button color="primary" onClick={toggle}><i class="fa fa-book"></i> Add to shelf </Button>
<Modal isOpen={modal} toggle={toggle}>
<ModalHeader toggle={toggle}>Add to shelf</ModalHeader>
<ModalBody>
<Form onSubmit={e => onSubmit(e)}>
<FormGroup row>
<Label for="exampleSelect" sm={2}>Status</Label>
<Col sm={6}>
<Input type="select" name="Add to" id="exampleSelect" placeholder="* select a shelf" value={status} onChange={e => onChange(e)} required>
<option value=''></option>
<option value='plan to read'>plan to read</option>
<option value='reading'>reading</option>
<option value='completed'>completed</option>
<option value='dropped'>dropped</option>
</Input>
</Col>
</FormGroup>
<FormGroup row>
<Label for="exampleSelect" sm={2}>Rating</Label>
<Col sm={4}>
<Input type="select" name="rating" placeholder="(optional)" id="exampleSelect" value={rating} onChange={e => onChange(e)}>
<option value =''>(optional)</option>
<option value ='1'>1</option>
<option value ='2'>2</option>
<option value ='3'>3</option>
<option value ='4'>4</option>
<option value ='5'>5</option>
</Input>
</Col>
</FormGroup>
<FormGroup row>
<Label for="exampleText" sm={2}>Review</Label>
<Col sm={9}>
<Input type="textarea" name="review" placeholder="(optional)" id="exampleText" value={review} onChange={e => onChange(e)} />
</Col>
</FormGroup>
<Button type ="submit" color="primary" >save</Button>{' '}
<Button color="secondary" onClick={toggle}>Cancel</Button>
</Form>
</ModalBody>
</Modal>
</center>
</article>
</aside>
<aside class="col-sm-7">
<article class="card-body p-5">
<h3 class="title mb-3">{bookDetails.bookName}</h3>
<dl class="param param-feature">
<dt>Rating</dt>
<dd>
<span class="float-center"><i class="text-warning fa fa-star"></i></span>
<span class="float-center"><i class="text-warning fa fa-star"></i></span>
<span class="float-center"><i class="text-warning fa fa-star"></i></span>
{' '}3.05
</dd>
</dl>
<dl class="item-property">
<dt>Description</dt>
<dd><p>{bookDetails.bookDescription}</p></dd>
</dl>
<dl class="param param-feature">
<dt>Author</dt>
<dd>someone</dd>
</dl>
<dl class="param param-feature">
<dt>Publish date</dt>
<dd>some date</dd>
</dl>
<dl class="param param-feature">
<dt>Genres</dt>
<dd>{
bookDetails.bookGenre.map(x=>x + ', ')}</dd>
</dl>
</article>
</aside>
</Row>
</Card>
</Container>
{/* review container */}
<Container style={{paddingTop: "1.5rem",paddingBottom: "1.5rem"}}>
<hr/>
<h2 style={{paddingTop: "1.5rem",paddingBottom: "1.5rem"}}>Reviews</h2>
<Card>
<CardBody>
<Row>
<Col md="12">
<p>
<strong>some one</strong>
<span class="float-right"><i class="text-warning fa fa-star"></i></span>
<span class="float-right"><i class="text-warning fa fa-star"></i></span>
<span class="float-right"><i class="text-warning fa fa-star"></i></span>
</p>
<div class="clearfix"></div>
<p>Lorem Ipsum is simply dummy text of the pr make but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
</Col>
</Row>
</CardBody>
</Card>
</Container>
</Fragment> )}
</Fragment>
)
)
BooksById.propTypes={
bookdetails: PropTypes.object.isRequired,
getBookById: PropTypes.func.isRequired
}
const mapStateToProps = state => ({
bookdetails: state.bookdetails
})
export default connect(mapStateToProps,{getBookById}) (BooksById);
这是我正在打电话的动作:
export const getBookById = (id) => dispatch => {
axios.get(`/api/booksDetails/${id}`)
.then(res=>{
dispatch({
type: GET_BOOKBYID,
payload: res.data
})
})
.catch(err=>{
dispatch({
type: BOOKDETAILS_FAIL,
payload: { msg: err.response.statusText, status: err.response.status }
})
})
}
这是减速器:
export default function (state = initialState, action) {
const { type, payload } = action;
switch (type) {
case GET_BOOKDETAILS:
case GET_BOOKBYGENRE:
return{
...state,
loading: false,
bookDetails: payload
}
case GET_BOOKBYID:
return{
...state,
loading: false,
bookDetails: payload
}
case BOOKDETAILS_FAIL:
return{
...state,
loading: false,
bookDetails: payload
}
default:
return state;
}
}
请帮助我解决我应该更改的问题,谢谢。
答案 0 :(得分:0)
首先,我建议您使用更简单的react redux钩子 for the documentation
首先,我建议您采取所有措施并将其放在一个文件中,而不要这样做
dispatch({
type: GET_BOOKBYID,
payload: res.data
})
因为它将使您的生活更加轻松,并且可以查看使用此功能的人是否出错了以及在哪里使用 关于您的问题,我认为您需要在connect参数中像这样传递它:
const mapDispatchToProps = dispatch => {
return {
onUpdate: (employee) => dispatch(actionTypes.UpdateEmployeeFetch(employee))
}
}
我记得您需要像这样通过它,否则什么也不会发生(我也发生了这种情况!) 如果您决定使用挂钩版本,则可以这样做:
const dispatch = useDispatch();
const addToFavorite = useCallback(
(key) => dispatch(actionCreators.addExistedCity(key)),
[dispatch]
)