我正在使用免费的API实现redux以获取数据。有人能解释一下我为什么会出现这个错误,以及解决这个问题的方法是什么吗。
action.js
export const tesla = () =>{
return (dispatch) => {
dispatch({
type:'tesla',
payload:
"https://newsapi.org/v2/everything?q=tesla&from=2022-07-17&sortBy=publishedAt&apiKey=b1e1719ca0724ff9bd9dab0645884e9a"
})
}
}
export const business = ()=>{
return (dispatch)=>{
dispatch({
type:'business',
payload:
"https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=b1e1719ca0724ff9bd9dab0645884e9c"
})
}
}
ApiReducer.js:
import React,{useState} from "react";
import axios from "axios";
const ApiReducer = (state=0,action) =>{
const type=action.type;
const [eror,setEror] = useState({});
const data = axios.get(action.payload).
then(data=>console.log(data)).catch(
error=>{
console.log(error);
setEror(error);
}
);
if(eror.length!==0) return eror;
return data;
}
export default ApiReducer;
CombineReducer.js:
import { combineReducers } from "@reduxjs/toolkit";
import ApiReducer from "./ApiReducer";
const CombineReducer = combineReducers({
value:ApiReducer
});
export default CombineReducer;
Store.js
import { configureStore } from "@reduxjs/toolkit";
import thunk from 'redux-thunk';
import reducers from "../reducers/CombineReducer";
const Store = configureStore({
reducer:reducers,
preLoadedState:{},
middleware:[thunk]
});
export default Store;
exportAction.js
export * as actions from './actions/action';
Rexercise.js
import React,{useState} from "react";
import {useSelector} from 'react-redux';
import { useDispatch } from "react-redux/es/exports";
import { actions } from "./redux";
const Rexercise = ()=>{
const [data,setData] = useState({});
data = useSelector(state=>state.value);
const dispatch = useDispatch();
const Tesla = ()=>{
setData(dispatch(actions.tesla()));
}
const Business = ()=>{
setData(dispatch(actions.business()));
}
return(
<div class="container">
<h1>Hello World</h1>
<button class="btn btn-primary" onClick={()=>Tesla()}>Tesla</button>
<button class=" mx-2 btn btn-success" onClick={()=>Business()}>Business</button>
<div className="article text-primary">
{data}
</div>
</div>
)
}
export default Rexercise;
我为这个应用程序提供了index.html中的商店。我得到的错误:
未捕获的类型错误:无法读取null的属性(读取"useState"(在useState(react.development.js:1622:1(
at ApiReducer (ApiReducer.js:6:1)
at redux.js:468:1
at Array.forEach (<anonymous>)
at assertReducerShape (redux.js:466:1)
at combineReducers (redux.js:531:1)
at ./src/components/redux/reducers/CombineReducer.js (CombineReducer.js:4:1)
at options.factory (react refresh:6:1)
at __webpack_require__ (bootstrap:24:1)
at fn (hot module replacement:62:1)
您的ApiReducer
不是减速器。您不能在那里调用异步方法,也不能在那里使用useState
。最重要的是,你在这里写的是一种风格的Redux,它是>3年的过时和超过4倍的代码现代Redux将是。
请遵循官方的Redux教程-无论你现在关注的是什么资源,都会给你过时的,可能是完全错误的指示。