我是新来的反应,并试图理解为什么我会看到这个错误:
Error: could not find react-redux context value; please ensure the component is wrapped in a <Provider>
Run Code Online (Sandbox Code Playgroud)
应用程序.js
export default function App() {
const selectedNumber = useSelector(selectChosenNumber) // This line causes the error
function pickedNumberHandler() {
console.log("called")
}
let screen = <StartGameScreen />;
pickedNumberHandler()
store.subscribe(pickedNumberHandler)
return (
<Provider store={store}>
<LinearGradient colors={['#4e0329', '#ddb52f']} style={styles.rootScreen}>
<ImageBackground
source={require('./assets/images/background.png')}
resizeMode="cover"
style={styles.rootScreen}
imageStyle={{opacity: 0.15}}
>
{screen}
</ImageBackground>
</LinearGradient>
</Provider>
);
}
const styles = StyleSheet.create({
rootScreen: {
flex: 1,
}
})
Run Code Online (Sandbox Code Playgroud)
selectedNumberReducer.ts
export const chosenNumberSlice …Run Code Online (Sandbox Code Playgroud) 如果用户未注册,API 会抛出 401。但即使有错误,extraReducers 也会执行已完成的情况。500 和其他错误也会发生这种情况。
额外减速器
extraReducers: (builder) => {
builder
.addCase(login.pending, function (state) {
console.log("pending");
state.isLoading = true;
})
.addCase(login.fulfilled, (state, action) => {
console.log("fullfield");
state.isLoading = false;
state.user = action.payload;
state.isAuthenticated = true;
})
.addCase(login.rejected, (state, action) => {
console.log("rejected");
console.log(action.payload);
state.isLoading = false;
state.error = true;
state.message = action.payload;
state.user = null;
});
}
Run Code Online (Sandbox Code Playgroud)
asyncThunk登录方法
export const login = createAsyncThunk("auth/login", async (user, thunkAPI) => {
try {
let user = await authService.login(user);
return user;
} catch (error) …Run Code Online (Sandbox Code Playgroud) 我正在使用useSelector钩子来检索我的减速器的值,但它导致我的应用程序上出现大量不必要的渲染。
我在组件上使用哪个属性并不重要,因为它们都state从减速器获取相同的对象,每次一个属性更改时,useSelector都会渲染所有使用的组件。
这是减速机:
const initialState = {
productsDataState: [], // => this is populated by multiple objects
searchProducts: [],
isSearchOn: false,
inputValue: '',
listOrder: [],
toastify: ['green', ''],
toastifyOpen: false
}
const reducer = ((state = initialState, action) => {
switch (action.type) {
case actionTypes.UPDATE_PRODUCT:
return {
...state,
productsDataState: action.products,
listOrder: action.listOrder
}
case actionTypes.SET_TOASTIFY:
return {
...state,
toastify: action.toastify,
toastifyOpen: action.open
}
case actionTypes.SET_SEARCH:
return {
...state,
searchProducts: action.searchProducts,
isSearchOn: action.isSearchOn,
inputValue: action.inputValue …Run Code Online (Sandbox Code Playgroud) 在我的应用程序中,我有一个令牌刷新端点/refresh,它在 cookie 中设置新的 JWT 刷新令牌并将新的 JWT 访问令牌作为 json 发送回。
由于访问令牌会在 5 分钟后过期,因此我需要在后台实现刷新逻辑,以便在访问令牌过期时启动。
目前我正在做的是通过调用api RTK Query,如果api拒绝查询,我调用refreshTokens突变。
我需要将此逻辑放入所有 api 查询中,如下所示:
updateProfile(body)
.unwrap()
.catch((error) => {
if (error && error.status === 403) {
refreshTokens(null); // RTK Query Mutation
updateProfile(body); // RTK Query Mutation
}
});
Run Code Online (Sandbox Code Playgroud)
这样做似乎是重复代码,因为它需要对所有 api 调用实现。
我想知道是否有一个全局解决方案可以在查询被拒绝时自动调用刷新令牌端点。
我正在尝试使用过滤器方法从数组中删除一个项目,如下所示:
removeDisplate: (state, action: PayloadAction<string>) => {
console.log(action.payload);
state.map((item) => {
console.log(item.name);
});
state.filter((item) => item.name !== action.payload);
},
Run Code Online (Sandbox Code Playgroud)
并从我的前端调用它,如下所示:
{cart.map((displate, index) => {
return (
<Card
sx={{
minHeight: "150px",
display: "flex",
padding: "10px",
gap: "10px",
backgroundColor: "black",
margin: "10px",
position: "relative",
}}
key={index}
>
<CloseIcon
sx={{
position: "absolute",
top: "10px",
right: "10px",
color: "red",
cursor: "pointer",
}}
onClick={() => handleRemoveDisplate(displate.name)}
/>
</Card>
);
})}
Run Code Online (Sandbox Code Playgroud)
状态中的有效负载和项目名称都与控制台日志相同,但它仍然没有从数组中删除它,有什么想法吗?
我一直在使用React v16的新生命周期。当我们仅比较单个键时,它的效果很好。但是,当要比较大型数据结构(如对象数组)时,深度比较将变得非常昂贵。
我有这样的用例,其中我有一个数组ob对象存储在redux中,
const readings =[
{
id: ...,
name: ...',
unit:...,
value: ...,
timestamp: ...,
active: true,
},
...
]
Run Code Online (Sandbox Code Playgroud)
每当任何对象的活动状态发生变化时,我都会调度一个操作,以将所有与该化简器连接的组件的redux状态更新为相同。
class Readings extends Component {
state = {
readings:[],
};
static getDerivedStateFromProps(nextProps, prevState) {
if ( // comparsion of readings array with prevState) {
return {
readings: nextProps.readings,
};
}
return null;
}
componentDidUpdate(prevProps) {
if ( // comparsion of readings array with prevState) {
// perform an operation here to manipulate new props and setState to re …Run Code Online (Sandbox Code Playgroud) 这是问题的.gif记录:http : //g.recordit.co/1gy4gyT7jk.gif
当我的Dashboard部件首先加载在登录后,我在控制台中返回以下错误。
Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.
in PlaidLink (at Dashboard.js:51)
in div (at Dashboard.js:44)index.js:1452
Run Code Online (Sandbox Code Playgroud)
尽管有此错误,但应用程序内部的所有内容都运行良好,并且在登录后刷新页面后,错误消失了(有关错误的示例,请参阅.gif)。
这是我的Login.js档案。
import React, { Component } from "react";
import { Link } from "react-router-dom";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import { …Run Code Online (Sandbox Code Playgroud) 我正在尝试学习redux-observable,但是在让我的应用返回数据时似乎出现了问题。我一直在下面看到错误,我不确定我要去哪里或该错误实际上意味着什么。
错误:类型错误:axios__WEBPACK_IMPORTED_MODULE_3 ___ default.a.get(...)。map不是函数
动作:
import { FETCH_DATA, FETCH_DATA_FAIL } from './constants';
export const fetchData = exampleData => ({
type: FETCH_DATA,
payload: { exampleData }
});
export const fetchDataFail = () => ({
type: FETCH_DATA_FAIL
});
Run Code Online (Sandbox Code Playgroud)
史诗:
import 'rxjs';
import { FETCH_DATA, FETCH_DATA_FAIL } from './constants';
import { fetchData } from './actions';
import axios from 'axios';
import { Observable } from 'rxjs';
import { mergeMap } from 'rxjs/operators';
import { ofType } from 'redux-observable';
export const exampleEpic = action$ => …Run Code Online (Sandbox Code Playgroud) 在我的create-react-app / redux中,我有一个“连接的组件”:
import React from "react";
import "./App.css";
import { connect } from "react-redux";
function App() {
debugger;
const { datas } = this.props;
debugger;
return <div className="App">{datas}}</div>;
}
const mapStateToProps = state => {
return {
datas: state
};
};
// const mapDispatchToProps = dispatch => {
// return {
// onRequestDog: () => dispatch({ type: "API_CALL_REQUEST_POST" })
// };
// };
export default connect(
mapStateToProps,
{}
)(App);
Run Code Online (Sandbox Code Playgroud)
Redux在index.js中配置:
import React from 'react';
import ReactDOM from 'react-dom';
import …Run Code Online (Sandbox Code Playgroud) 在全栈应用程序上工作时,我正在调用后端,该后端从数据库检索信息并将其返回。问题是,当我期望获得价值时,我只会得到Promise {<pending>}。我已经在后端代码上验证了我实际上是从数据库获得响应并将其发送回前端的,所以我不确定为什么诺言没有得到解决。有任何想法/建议吗?
这是我尝试调用后端并显示信息的组件。该console.log是什么样的显示Promise {<pending>}
getTheAsset = async id => {
try {
const response = await this.props.getAsset(id)
.then(result => {
console.log("[DisplayAsset] Promise result: ", result);
});
} catch(error) {
console.log("[DisplayAsset] error: ", error);
}
}
render() {
const asset = this.getTheAsset(this.props.match.params.id);
console.log("[DisplayAsset] asset - ", asset);
return (
<div className="container">
</div>
);
}
Run Code Online (Sandbox Code Playgroud)
以下是进行API调用的redux操作。
export const getAsset = (id) => async dispatch => {
const response = await axios.get(`http://localhost:8181/api/asset/${id}`);
dispatch({
type: GET_ASSET,
payload: response.data
}); …Run Code Online (Sandbox Code Playgroud) reactjs ×10
redux ×10
javascript ×4
react-redux ×2
redux-thunk ×2
jwt ×1
material-ui ×1
promise ×1
react-hooks ×1
rtk-query ×1
typescript ×1