javascript - React redux 不更新全局状态

标签 javascript reactjs redux react-redux

我正在使用没有钩子(Hook)的 Redux,并且所有似乎都完美地捆绑在一起,但是当我查看浏览器控制台 Redux 窗口时,我的状态没有改变。所以基本上我有一个看起来像这样的商店文件

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
然后我有我的全局 reducer 文件
import {combineReducers} from "redux";
import searchReducer from './searchReducer'

export default combineReducers({
    books: searchReducer
})
和 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
    }
}
现在我只有你看到的 Action 类型导入那里
这是那个 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));
};

一切都在应用程序中捆绑在一起,我在其中导入了包含所有内容的提供程序。
问题来了。我有一个搜索表单,应该在更改时更新全局状态的查询值
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

我不知道缺少什么。
编辑
正如建议的那样,我尝试使用钩子(Hook),现在一切都很好地捆绑在一起。现在的问题是取书。我更新了 Action 文件,以便您可以看到我添加的 Action 。当我发送此操作时,我收到此错误

Actions must be plain objects. Use custom middleware for async actions


有人知道如何解决这个问题吗?

最佳答案

我想你的错误可以解决为

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));
};

关于javascript - React redux 不更新全局状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63835117/

相关文章:

javascript - 触发操作时出现回流错误

reactjs - 如何在 antd 表组件上设置默认排序器和过滤器?

reactjs - react history.push 需要 forceRefresh

javascript - 如何采取通过阻塞调用调度的多个操作

javascript - 如何检测 Angular 中复制对象的更改?

javascript - 隐藏/显示时列表元素动画不起作用

reactjs - material-ui reactjs中的嵌套抽屉

javascript - OwnProps Match 和 Params 未定义 React-Router V3

javascript - 当用户从下拉列表中选择一个选项时,提交()表单是不好的做法吗?

javascript - 两个for循环内的node.js同步请求