我正在构建一个小应用程序来学习如何使用 Redux 工具包(我对 React/Redux 的了解主要来自过时的 Udacity 课程)。
错误消息给出了弹出此错误的前 3 个原因,但似乎其中任何一个都不适用于我。
- React 和 React DOM 的版本不匹配?我的两个都被列为依赖项并且具有相同的版本。
- 打破 Hooks 的规则?不使用我知道的任何钩子。我所有的组件都是类组件(Udacity,还记得吗?)。此外,我已经从 App 组件的
render()
调用中删除了所有组件,并且错误仍然存在。 - 不止一份 React?
npm ls react
只显示一个版本。
我不太确定从这里去哪里。每当我从ReactDOM.render()
调用中删除 Provider 时,错误就会消失。
我已经盯着这个有一段时间了,我什么也没有。发布我认为是下面的相关代码。
我目前有一个减速器:
/src/features/mortgage/mortgageSlice.ts
import { createSlice } from '@reduxjs/toolkit'
interface MortgageState {
principal?: number
rate?: number
term?: number
closingCosts?: number
amortization?: { payment: number; schedule: Array<any> }
}
const payment = (rate: number, nper: number, pv: number) => {
const pvif = Math.pow(1 + rate / 100, nper)
return (rate / (pvif - 1)) * -(pv * pvif)
}
const computeSchedule = (
principal: number,
apr: number,
nper: number,
payment: number
) => {
let schedule = []
let remaining = principal
for (let i = 0; i <= nper; i++) {
// apr percent / 100 (to decimal) / 12 (months in a year)
const interest = remaining * (apr / 100 / 12)
const principal = payment - interest
const row = [
i,
principal > 0 ? principal : 0,
interest > 0 ? interest : 0,
remaining > 0 ? remaining : 0,
]
schedule.push(row)
remaining -= principal
}
return schedule
}
const initialState: MortgageState = {}
const mortgageSlice = createSlice({
name: 'mortgage',
initialState,
reducers: {
updateMortgageParams(state, action) {
const { principal, rate, term, closingCosts } = action.payload
state.principal = principal
state.rate = rate
state.term = term
state.closingCosts = closingCosts
},
amortize(state, action) {
const { principal, rate, term } = state
if (principal && rate && term) {
const pmt = payment(rate, term * 12, principal)
const schedule = computeSchedule(principal, rate, term * 12, pmt)
state.amortization = { payment: pmt, schedule }
}
},
},
})
export const { updateMortgageParams, amortize } = mortgageSlice.actions
export default mortgageSlice.reducer
根减速器:
/src/app/rootReducer.ts
import { combineReducers } from '@reduxjs/toolkit'
import mortgage from '../features/mortgage/mortgageSlice'
export default combineReducers({
mortgage
})
店铺:
/src/app/store.ts
import { configureStore } from '@reduxjs/toolkit'
import rootReducer from './rootReducer'
const store = configureStore({
reducer: rootReducer
})
export default store
/src/index.tsx
import React from 'react'
import ReactDOM from 'react-dom'
import './index.css'
import App from './app/App'
import * as serviceWorker from './serviceWorker'
import store from './app/store'
import { Provider } from 'react-redux'
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>,
document.getElementById('root')
)