[英]React redux not updating global state
I am using Redux without hooks and all seem to be tied together perfectly, but when I look in the browser console Redux window my state doesn't change.我正在使用没有钩子的 Redux,并且所有这些似乎都完美地结合在一起,但是当我查看浏览器控制台 Redux 窗口时,我的状态没有改变。 So basically I have a store file which looks like this所以基本上我有一个看起来像这样的商店文件
import {createStore, applyMiddleware} from "redux";
import thunk from 'redux-thunk'
import {composeWithDevTools} from "redux-devtools-extension/developmentOnly";
import rootReducer from './reducers'
const middleware = [thunk]
const initialState = {}
const store = createStore(rootReducer, initialState,composeWithDevTools(applyMiddleware(...middleware)))
export default store
then I have my global reducer file然后我有我的全局减速器文件
import {combineReducers} from "redux";
import searchReducer from './searchReducer'
export default combineReducers({
books: searchReducer
})
and the searchReducers file和 searchReducers 文件
import {SEARCH_BOOK, SET_INDEX,FETCH_BOOKS} from "../actions/types";
const initialState = {
query: '',
books: [],
loading: false,
book: []
}
export default function (state = initialState, action) {
switch (action.type) {
case 'SEARCH_BOOK':
return {
...state,
query:action.payload,
loading: false
}
case 'SET_INDEX':
return {
...state,
index:action.payload,
loading: false
}
case 'FETCH_BOOKS':
return {
...state,
index:state.index+40,
books:state.books.concat(action.payload),
loading: false
}
default:
return state
}
}
for now I only have the action type you see imported there here is that action现在我只有你在这里看到的动作类型是那个动作
import {SEARCH_BOOK} from "./types";
export const searchBook = query => dispatch => {
dispatch ({
type:SEARCH_BOOK,
payload:query
})
}
export const fetchBooks = (query,index) => {
console.log(query)
axios
.get(`https://www.googleapis.com/books/v1/volumes?q=${query}&maxResults=40&orderBy=relevance&startIndex=${index}`)
.then(response =>{
return({
type: FETCH_BOOKS,
payload: response.data.items
})}
)
.catch(err => console.log(err));
};
All is tied together in the App where I imported the provider that wraps up everything.所有这些都在应用程序中捆绑在一起,我在其中导入了包装所有内容的提供程序。 Here comes the problem.问题来了。 I have a search form that should on change update the query value of the global state我有一个搜索表单,应该在更改时更新全局状态的查询值
import React, { useState, useReducer} from "react";
import {useSelector, useDispatch} from 'react-redux'
import { Button, Container, Row, Col, Form, FormGroup, FormInput } from "shards-react";
import queryBuilder from "../js/helper";
import style from "./SearchForm/body.module.css";
import {searchBook, fetchBooks} from "../actions/SearchActions";
const initialState = {
title:'',
author:'',
publisher:''
}
function reducer(state,{ field, value }){
return {
...state,
[field]: value
}
}
function SearchForm() {
const index = useSelector(state => state.index)
const [state, dispatch] = useReducer(reducer, initialState);
const [query, setQuery] = useState('');
const disp = useDispatch();
const onChange = e => {
dispatch({ field: e.target.name, value: e.target.value })
}
const { title,author,publisher } = state;
const handleSubmit = e => {
e.preventDefault()
setQuery(queryBuilder(state))
disp(fetchBooks(query, 0))
}
return(
<div>
<Container className={style.FormContainer}>
<Form onSubmit={handleSubmit}>
<Row className={'topBar'}>
<Col>
<FormGroup>
<FormInput id={'bookTitle'} name={'title'} placeholder={'title'} value={title} onChange={onChange}/>
</FormGroup>
</Col>
<Col>
<FormGroup>
<FormInput id={'bookAuthor'} name={'author'} value={author} onChange={onChange} placeholder={'author'}/>
</FormGroup>
</Col>
<Col>
<FormGroup>
<FormInput id={'bookPublisher'} name={'publisher'} value={publisher} onChange={onChange}
placeholder={'publisher'}/>
</FormGroup>
</Col>
<Col>
<Button outline theme='primary' type={'submit'}>Submit</Button>
</Col>
</Row>
</Form>
</Container>
</div>
)
}
export default SearchForm
I don't know what is missing.我不知道缺少什么。
Edit As suggested I tried using hooks and now everything is tied together just fine.编辑正如建议的那样,我尝试使用钩子,现在一切都很好地捆绑在一起。 The problem is now with the fetching of the books.现在的问题是取书。 I updated the action file so you can see the action I added.我更新了操作文件,以便您可以看到我添加的操作。 When I dispatch this action I get this error当我调度此操作时,我收到此错误
Actions must be plain objects.动作必须是普通对象。 Use custom middleware for async actions使用自定义中间件进行异步操作
Does anybody know how to fix this?有谁知道如何解决这个问题?
I guess your error can be resolved as我想你的错误可以解决为
export const fetchBooks =(query,index) => dispatch => {
console.log(query)
axios
.get(`https://www.googleapis.com/books/v1/volumes?q=${query}&maxResults=40&orderBy=relevance&startIndex=${index}`)
.then(response =>{
dispatch({
type: FETCH_BOOKS,
payload: response.data.items
})}
)
.catch(err => console.log(err));
};
It looks like you're missing a return
in your fetchBooks
function.看起来您在fetchBooks
函数中缺少return
值。 You're not returning the promise, which means that the thunk middleware isn't receiving the promise result.您没有返回承诺,这意味着 thunk 中间件没有收到承诺结果。
export const fetchBooks = (query,index) => {
console.log(query)
return axios
.get(`https://www.googleapis.com/books/v1/volumes?q=${query}&maxResults=40&orderBy=relevance&startIndex=${index}`)
.then(response =>{
return({
type: FETCH_BOOKS,
payload: response.data.items
})}
)
.catch(err => console.log(err));
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.