redux-persist 相关问题


“在‘redux’中找不到导出‘createStore’

./node_modules/@redux-saga/core/dist/redux-saga-core.esm.js 中的警告 1343:21-28 “在‘redux’中找不到导出‘compose’ @ ./node_modules/redux-saga/dist/redux-saga-core-npm-proxy.esm.js ...


TypeScript Redux 在刷新页面时丢失状态

redux/reducer/cartReducer.ts 从“@reduxjs/toolkit”导入{createSlice,PayloadAction}; 从“../../types/reducer-types”导入{ CartReducerInitialState }; 导入 { 购物车项目,


为什么 Context API 在高频更新方面比 Redux 差?

我看到很多文章说Redux比高频更新在性能上比Context API更好,但没有具体说明原因。 是什么让人们说 Redux 比 Context API 更好......


React store.getState 不是一个函数

这是我的代码: 商店.js 从 'redux' 导入 {createStore, applyMiddleware, compose}; 从“不可变”导入{fromJS}; 从“react-router-redux”导入{routerMiddleware}; 导入createSagaMidd...


如何使用 redux tollkit 修复 Next 14 中的错误“请确保组件包裹在 <Provider> 中”?

我很难让 Next.js 14 与 Redux Provider 一起使用。我按照 Redux 官方文档上的所有说明进行操作,但我不断收到此错误: 错误:找不到反应-...


使用包装器时从非函数组件调用 React-Redux 调度函数

我有一个 React-Redux 存储,它包装在 next-redux-wrapper 中。我想在 React 组件之外调度一个函数,但由于包装器的原因我无法这样做。有办法导入吗


使用包装器时从非功能组件调用 React-Redux Dispatch 函数

我确实有一个react redux store,它包装在next-redux-wrapper中。我想在 React 组件之外调度一个函数,但由于包装器的原因我无法这样做。有没有办法让我...


Redux 工具包解析非 JSON 响应时出错

我正在尝试 redux 工具包,目前有以下切片和突变: 导出 const apiSlice = createApi({ 减速器路径:“api”, 基本查询: fetchBaseQuery({ 基本网址:“


React-Redux useSelector typescript type for state

我正在使用 React-Redux 中的 useSelector(state => state.SLICE_NAME) 挂钩,但是我在定义状态参数时遇到了困难。它默认设置为未知,因此当我尝试时会收到错误...


如何在 RTL 测试中使用 React Redux useDispatch 钩子?

我想在使用 redux 调度后测试 React 组件。我正在使用“test-utils.ts”文件中的自定义渲染函数: 从 'react' 导入 { ReactElement } 导入{渲染,渲染O...


我如何从react-redux中的api调用的数据中过滤值

我正在使用react和redux从API调用中获取数据,现在我创建了一个新变量并为其分配了相同的数据。在代码中,我将操作这个名为


使用 Redux 和 Typescript,如何正确键入“mapStateToProps”函数以仅允许通过状态传递 3 个参数中的 2 个?

我正在将 React 18 与 Redux 8 和 Typescript 结合使用。我想创建一个组件,允许调用者传入其中一个参数,但其他两个参数是从状态派生的。所以我创建了


Typescript 无法与 tsconfig.json 一起使用

在项目中使用 tsconfig 运行 tsc --watch 时,出现以下错误。 它需要 Node js 中的 React 和 Redux 类型。 错误 TS2688:找不到“abstract-leveldow...”的类型定义文件...


在操作中检测到不可序列化的值(redux-toolkit)

在store中action的payload中,我使用File类型存储下载的文件,然后该文件将在saga中通过验证 const form = new FormData(); if (私钥 &&


反应单元测试“不是函数”对象。<anonymous>

努力为使用 redux/sagas 的文件编写一些单元测试。 app.tsx 文件看起来像这样 从 'react' 导入 React, { StrictMode } 从'react-dom'导入ReactDOM 导入 { Provider } f...


升级到 React 18 后 React App 未渲染

`我的 React 应用程序运行良好,但升级到 React 18、mui v5 和 redux v5 后,它没有渲染任何内容。 在终端中,我得到: webpack 编译成功 但在 chrome 控制台中...


office 插件中的 Redux DevTools

我正在开发一个使用 Angular 15 的 Excel 插件,在 Angular 应用程序中,我刚刚添加了 @ngrx/store。我也将开发工具添加到了模块中。我注意到 Excel 使用 Edge 来运行该加载项。


使用 WebSocket 和 React 构建通知面板时的推荐方法

我正在使用 websocket 和 React 构建一个通知面板。我应该使用 redux 工具包还是 useContext 来管理 Websocket 的集中位置?或者还有其他建议的方法吗...


如何在 Redux Saga 中使用 React Hook?

我正在为我的应用程序设置语言。但我有一个问题。 我使用 React.useContext() 来设置语言。但是当我在 saga 的 toast 中修复它时,它会记录: [错误:无效的挂钩调用。 Hooks 只能在 ins 中调用...


此悬念边界在完成水合之前收到了更新。 React Native、Expo 路由器、Redux、Supabase

在 Expo 上启动开发服务器,在 localhost:8081 上的浏览器上打开,期望应用程序呈现,但出现错误: 这个悬念边界在完成水合之前收到了更新。这...


使用 StructureMap 连接不同的实现

我有一个非常简单的通用存储库: 公共接口IRepository 其中 TEntity : EntityObject 其中 TNotFound : TEntity, new() { 列表 我有一个非常简单的通用存储库: public interface IRepository<TEntity, TNotFound> where TEntity : EntityObject where TNotFound : TEntity, new() { IList<TEntity> GetAll(); TEntity With(int id); TEntity Persist(TEntity itemToPersist); void Delete(TEntity itemToDelete); } 我想为 Term 类型的存储库定义一个合约,没有任何特殊行为。所以它看起来像这样: public class TermNotFound : Term { public TermNotFound() : base(String.Empty, String.Empty) { } } public interface ITermRepository : IRepository<Term, TermNotFound> { } 现在为了测试,我想创建通用存储库的内存中实现,所以我有这个(为简洁起见,未完成): public class InMemoryRepository<TEntity, TNotFound> : IRepository<TEntity, TNotFound> where TEntity : EntityObject where TNotFound : TEntity, new() { private IList<TEntity> _repo = new List<TEntity>(); public IList<TEntity> GetAll() { return this._repo; } public TEntity With(int id) { return this._repo.SingleOrDefault(i => i.Id == id) ?? new TNotFound(); } public TEntity Persist(TEntity itemToPersist) { throw new NotImplementedException(); } public void Delete(TEntity itemToDelete) { throw new NotImplementedException(); } } 不难看出我希望它如何工作。对于我的测试,我希望注入通用 InMemoryRepository 实现来创建我的 ITermRepository。 好吧,我无法让 StructureMap 来做这件事。我尝试在扫描仪中使用 WithDefaultConventions 和 ConnectImplementationsToTypesClosing(typeof(IRepository<,>)) 但没有成功。接下来我可以尝试什么? 您的 InMemoryRepository 未实现 ITermRepository 接口。这就是为什么你无法连接它们。 你能用你所拥有的最好的办法就是注射 InMemoryRepository<Term, TermNotFound> 以获得 IRepository<Term, TermNotFound>。 如果你确实需要注入ITermRepository,那么你需要有另一个存储库类继承InMemoryRepository并实现ITermRepository: public class InMemoryTermRepository : InMemoryRepository<Term, TermNotFound>, ITermRepository { } 现在您可以使用以下方法将 ITermRepository 连接到 InMemoryTermRepository: .For<ITermRepository>().Use<InMemoryTermRepository>() 如果您有很多像 ITermRepository 这样的接口,您可以创建一个 StructureMap 约定,将 I...Repository 连接到 InMemory...Repository。默认约定是将 IClass 连接到 Class。


Flatpickr AlpineJS 在危险范围选择上坚持插件

我有一个工作完美的 Flatpickr 日期范围日历,它将日期存储在会话存储中。这是我的代码: 我有一个工作完美的 Flatpickr 日期范围日历,它将日期存储在会话存储中。这是我的代码: <div x-data="{ chosenDates: sessionStorage.getItem('_x_range'), value: [], init() { let picker = flatpickr(this.$refs.picker, { mode: 'range', inline: false, dateFormat: 'm/d/Y', showMonths: 2, }) this.$watch('value', () => picker.setDate(this.value)) }, }" > <div class="flex items-center flex-1 gap-2 overflow-hidden border border-gray-500 rounded-lg"> <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="ml-4 bi bi-calendar-event-fill" viewBox="0 0 16 16"> <path d="M4 .5a.5.5 0 0 0-1 0V1H2a2 2 0 0 0-2 2v1h16V3a2 2 0 0 0-2-2h-1V.5a.5.5 0 0 0-1 0V1H4zM16 14V5H0v9a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2m-3.5-7h1a.5.5 0 0 1 .5.5v1a.5.5 0 0 1-.5.5h-1a.5.5 0 0 1-.5-.5v-1a.5.5 0 0 1 .5-.5"/> </svg> <input id="rangeValue" :value="chosenDates" placeholder="Add dates" x-ref="picker" type="text" class="p-0 py-4 placeholder-gray-600 border-0 bg-none focus:ring-0 " data-input> </div> </div> 设置项目: function dateRange() { var date = document.getElementById("rangeValue").value; sessionStorage.setItem("_x_range", date); sessionStorage.setItem("start", start); sessionStorage.setItem("end", end); const start = sessionStorage.getItem("start"); } $('#rangeValue').on('focus', ({ currentTarget }) => $(currentTarget).blur()) $("#rangeValue").prop('readonly', false) ``` Receive item: if (sessionStorage.getItem("_x_range") != null) { document.getElementById("chosenRange").innerHTML = sessionStorage.getItem("_x_range"); document.getElementById("rangeValue").value = sessionStorage.getItem("_x_range"); } ``` 如果可能的话,我想学习如何使用 AplineJS 和 Persist 来设置它,以免代码过多而过期。 这可能吗? 这是一个可能的解决方案: <div x-data="{ thePicker: null, chosenDates: $persist([]).using(sessionStorage).as('_x_range'), init() { this.thePicker = flatpickr(this.$refs.picker, { mode: 'range', inline: false, dateFormat: 'm/d/Y', showMonths: 2, defaultDate: this.chosenDates, onChange: (selectedDates) => {this.chosenDates = [...selectedDates];} }); }, }" > <div class="flex items-center flex-1 gap-2 overflow-hidden border border-gray-500 rounded-lg"> <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="ml-4 bi bi-calendar-event-fill" viewBox="0 0 16 16"> <path d="M4 .5a.5.5 0 0 0-1 0V1H2a2 2 0 0 0-2 2v1h16V3a2 2 0 0 0-2-2h-1V.5a.5.5 0 0 0-1 0V1H4zM16 14V5H0v9a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2m-3.5-7h1a.5.5 0 0 1 .5.5v1a.5.5 0 0 1-.5.5h-1a.5.5 0 0 1-.5-.5v-1a.5.5 0 0 1 .5-.5"/> </svg> <input type="text" x-ref="picker" placeholder="Add dates" class="p-0 py-4 placeholder-gray-600 border-0 bg-none focus:ring-0" > <span title="Clear" class="text-blue-600 cursor-pointer" @click="thePicker.clear()" > X </span> </div> <div x-text="chosenDates"> </div> </div> 日期范围存储在 Alpine chosenDates 变量中,该变量通过 Persist 进行持久化并初始化为空数组。 当日期选择器初始化时,chosenDates变量用于填充defaultDate参数。 选择日期范围后,flatpicker 会触发 onChage 事件,因此我使用它将新范围复制到 chosenDates 变量中。 我添加了一个 “clear” 按钮以 flatpicker 方式重置输入字段,调用 clear() 方法(这是一个简单的示例),然后我必须将 flatpicker 引用存储在 thePicker 中变量. 我还添加了一个 通过 x-text 显示 choosenDates 的内容


将 props 传递给 nextjs 中的页面组件

我正在使用 nextjs 的 withlayout 函数为某些页面添加侧边栏。 导出类型 PageWithLayout = NextPage & { withLayout?:(页面:ReactElement)=> 我正在使用 nextjs 的 withlayout 函数为某些页面添加侧边栏。 export type PageWithLayout<P = {}, IP = P> = NextPage<P, IP> & { withLayout?: (page: ReactElement) => ReactNode; }; 这是我的使用方法: export const Interactions: PageWithLayout = () => { const [ getInteractions, { data: interactionData, fetchMore, variables, loading: isInteractionsLoading, error: isInteractionsError, }, ] = useGetInteractionsLazyQuery({ notifyOnNetworkStatusChange: true, fetchPolicy: "network-only", ssr: false, }); return ( <> <Box height={"100vh"}> </Box> </> ); }; Interactions.withLayout = (page: ReactElement) => { // how do I pass isInteractionsLoading as a prop to this component return <Layout>{page}</Layout>; }; export default Interactions; 我想要实现的是将 isInteractionsLoaded 和 isInteractionsError 作为属性传递给我的布局组件,以便我可以渲染这些状态。有没有一种方法可以实现此目的,而无需将布局组件移动到页面组件内? 创建一个包装组件的 React Context 提供程序可能是您使用的解决方案,如果您不想使用任何其他包或不想使用 redux 等更强大的工具,则可以使用。 但是在这里使用有点尴尬,具体取决于包含交互的组件树是什么样子。否则可以根据您的需要使用 _app 入口点。 示例上下文和用法 import React from 'react'; export const InteractionContext = React.createContext({ isInteractionsLoading: false, isInteractionsError: null, }); // parent component or _app if necessary const ProviderComponent = () => { return ( <InteractionContext.Provider value={{ isInteractionsLoading, isInteractionsError }}> <Interactions /> </InteractionContext.Provider> ); }; const Layout = ({ children }) => { const { isInteractionsLoading, isInteractionsError } = useContext(InteractionContext); // Now you can use isInteractionsLoading and isInteractionsError here // ... return <div>{children}</div>; };


SecurityException:不允许启动服务Intent { act=com.google.android.c2dm.intent.REGISTER pkg=com.google.android.gms (有额外功能)}

我尝试从 Google 获取我的 GCM 注册 ID。 我的代码: 字符串SENDER_ID =“722*****53”; /** * 向 GCM 服务器异步注册应用程序。 * * 存储注册信息... 我尝试从 Google 获取我的 GCM 注册 ID。 我的代码: String SENDER_ID = "722******53"; /** * Registers the application with GCM servers asynchronously. * <p> * Stores the registration ID and the app versionCode in the application's * shared preferences. */ private void registerInBackground() { new AsyncTask<Void, Void, String>() { @Override protected String doInBackground(Void... params) { String msg = ""; try { if (gcm == null) { gcm = GoogleCloudMessaging.getInstance(context); } regid = gcm.register(SENDER_ID); msg = "Device registered, registration ID=" + regid; // You should send the registration ID to your server over // HTTP, so it // can use GCM/HTTP or CCS to send messages to your app. sendRegistrationIdToBackend(); // For this demo: we don't need to send it because the // device will send // upstream messages to a server that echo back the message // using the // 'from' address in the message. // Persist the regID - no need to register again. storeRegistrationId(context, regid); } catch (IOException ex) { msg = "Error :" + ex.getMessage(); // If there is an error, don't just keep trying to register. // Require the user to click a button again, or perform // exponential back-off. } return msg; } @Override protected void onPostExecute(String msg) { mDisplay.append(msg + "\n"); } }.execute(null, null, null); } 我收到错误: 03-01 19:15:36.261: E/AndroidRuntime(3467): FATAL EXCEPTION: AsyncTask #1 03-01 19:15:36.261: E/AndroidRuntime(3467): java.lang.RuntimeException: An error occured while executing doInBackground() 03-01 19:15:36.261: E/AndroidRuntime(3467): at android.os.AsyncTask$3.done(AsyncTask.java:299) 03-01 19:15:36.261: E/AndroidRuntime(3467): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352) 03-01 19:15:36.261: E/AndroidRuntime(3467): at java.util.concurrent.FutureTask.setException(FutureTask.java:219) 03-01 19:15:36.261: E/AndroidRuntime(3467): at java.util.concurrent.FutureTask.run(FutureTask.java:239) 03-01 19:15:36.261: E/AndroidRuntime(3467): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230) 03-01 19:15:36.261: E/AndroidRuntime(3467): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080) 03-01 19:15:36.261: E/AndroidRuntime(3467): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573) 03-01 19:15:36.261: E/AndroidRuntime(3467): at java.lang.Thread.run(Thread.java:841) 03-01 19:15:36.261: E/AndroidRuntime(3467): Caused by: java.lang.SecurityException: Not allowed to start service Intent { act=com.google.android.c2dm.intent.REGISTER pkg=com.google.android.gms (has extras) } without permission com.google.android.c2dm.permission.RECEIVE 03-01 19:15:36.261: E/AndroidRuntime(3467): at android.app.ContextImpl.startServiceAsUser(ContextImpl.java:1800) 03-01 19:15:36.261: E/AndroidRuntime(3467): at android.app.ContextImpl.startService(ContextImpl.java:1772) 03-01 19:15:36.261: E/AndroidRuntime(3467): at android.content.ContextWrapper.startService(ContextWrapper.java:480) 03-01 19:15:36.261: E/AndroidRuntime(3467): at com.google.android.gms.gcm.GoogleCloudMessaging.b(Unknown Source) 03-01 19:15:36.261: E/AndroidRuntime(3467): at com.google.android.gms.gcm.GoogleCloudMessaging.register(Unknown Source) 03-01 19:15:36.261: E/AndroidRuntime(3467): at com.example.gcm.DemoActivity$1.doInBackground(DemoActivity.java:177) 03-01 19:15:36.261: E/AndroidRuntime(3467): at com.example.gcm.DemoActivity$1.doInBackground(DemoActivity.java:1) 03-01 19:15:36.261: E/AndroidRuntime(3467): at android.os.AsyncTask$2.call(AsyncTask.java:287) 03-01 19:15:36.261: E/AndroidRuntime(3467): at java.util.concurrent.FutureTask.run(FutureTask.java:234) 03-01 19:15:36.261: E/AndroidRuntime(3467): ... 4 more 这是我的清单: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.manyexampleapp" android:installLocation="preferExternal" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="11" android:targetSdkVersion="18" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.GET_ACCOUNTS" /> <uses-permission android:name="android.permission.WAKE_LOCK" /> <uses-permission android:name="com.example.manyexampleapp.c2dm.permission.RECEIVE" /> <uses-permission android:name="com.example.manyexampleapp.gcm.permission.C2D_MESSAGE" /> <permission android:name="com.example.manyexampleapp.gcm.permission.C2D_MESSAGE" android:protectionLevel="signature" /> <application android:name="com.zoomer.ifs.BaseApplication" android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" /> <activity android:name="com.zoomer.ifs.MainActivity" android:label="@string/app_name" android:configChanges="orientation|keyboardHidden|screenSize" android:launchMode="singleTop"> <!-- <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> --> </activity> <!-- PUSH --> <!-- WakefulBroadcastReceiver that will receive intents from GCM services and hand them to the custom IntentService. The com.google.android.c2dm.permission.SEND permission is necessary so only GCM services can send data messages for the app. --> <receiver android:name="com.example.gcm.GcmBroadcastReceiver" android:permission="com.google.android.c2dm.permission.SEND" > <intent-filter> <!-- Receives the actual messages. --> <action android:name="com.google.android.c2dm.intent.RECEIVE" /> <category android:name="com.example.manyexampleapp" /> </intent-filter> </receiver> <service android:name="com.example.gcm.GcmIntentService" /> <activity android:name="com.example.gcm.DemoActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <!-- DB --> <activity android:name="com.example.db.DbActivity" android:label="@string/app_name" > <intent-filter> </intent-filter> </activity> <activity android:name="com.example.http.RestGetActivity" android:label="@string/app_name" android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen" > </activity> <activity android:name="com.example.fb.FacebookLoginActivity" android:label="@string/app_name" > <!-- <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> --> </activity> <activity android:name="com.example.http.SendFeedbackActivity" android:label="@string/app_name" > <!-- <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> --> </activity> <activity android:name="com.zoomer.general.SearchNearbyOffersActivity" android:label="@string/app_name" > <intent-filter> </intent-filter> </activity> <activity android:name="com.facebook.LoginActivity" android:label="@string/app_name" > <intent-filter> </intent-filter> </activity> <activity android:name="com.example.manyexampleapp.StoresListActivity" > <intent-filter> </intent-filter> </activity> <activity android:name="com.example.fb.ShareActivity" > <intent-filter> </intent-filter> </activity> <activity android:name="com.example.notifications.NotificationsActivity" > <intent-filter> </intent-filter> </activity> <activity android:name="com.example.fb2.no_use.MainActivity" > <intent-filter> </intent-filter> </activity> <activity android:name="com.zoomer.offers.OffersListActivity" > <!-- <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> --> </activity> <activity android:name="com.example.http.SearchNearbyOffersActivity" > <!-- <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> --> </activity> <service android:name="com.example.geo.LocationService" android:enabled="true" /> <receiver android:name="com.example.manyexampleapp.BootReceiver" > <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> <action android:name="com.example.manyexampleapp.LocationService.LOCATION_BROAD_MSG" /> </intent-filter> </receiver> <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/app_id" /> </application> </manifest> 改变 <uses-permission android:name="com.example.manyexampleapp.c2dm.permission.RECEIVE" /> 到 <!-- This app has permission to register and receive data message. --> <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" /> 您收到异常是因为您尚未定义所需的权限 如果应用程序开发后安装了播放服务, 可能会发生 com.google.android.c2dm.permission.RECEIVE 权限已被授予但 android 仍在抱怨同样的错误。 在这种情况下,您必须完全重新安装开发的应用程序才能使此权限发挥作用。 我认为你必须检查 Kotlin 版本兼容性。


如何防止点击时嵌套 React 组件中的事件冒泡?

这是一个基本组件。 和 都有 onClick 函数。我只想触发 上的 onClick,而不是 。我怎样才能实现这个目标? 我玩过 这是一个基本组件。 <ul> 和 <li> 都有 onClick 函数。我只想触发 <li> 上的 onClick,而不是 <ul>。我怎样才能实现这个目标? 我尝试过 e.preventDefault()、e.stopPropagation(),但无济于事。 class List extends React.Component { constructor(props) { super(props); } handleClick() { // do something } render() { return ( <ul onClick={(e) => { console.log('parent'); this.handleClick(); }} > <li onClick={(e) => { console.log('child'); // prevent default? prevent propagation? this.handleClick(); }} > </li> </ul> ) } } // => parent // => child 我也有同样的问题。我发现 stopPropagation did 有效。我会将列表项拆分为一个单独的组件,如下所示: class List extends React.Component { handleClick = e => { // do something } render() { return ( <ul onClick={this.handleClick}> <ListItem onClick={this.handleClick}>Item</ListItem> </ul> ) } } class ListItem extends React.Component { handleClick = e => { e.stopPropagation(); // <------ Here is the magic this.props.onClick(); } render() { return ( <li onClick={this.handleClick}> {this.props.children} </li> ) } } React 使用事件委托和文档上的单个事件侦听器来处理冒泡事件,例如本例中的“单击”,这意味着不可能停止传播;当您在 React 中与真实事件交互时,真实事件已经传播。 React 的合成事件上的 stopPropagation 是可能的,因为 React 在内部处理合成事件的传播。 stopPropagation: function(e){ e.stopPropagation(); e.nativeEvent.stopImmediatePropagation(); } 关于 DOM 事件的顺序:CAPTURING vs BUBBLING 事件传播有两个阶段。这些被称为 “捕获” 和 “冒泡”。 | | / \ ---------------| |----------------- ---------------| |----------------- | element1 | | | | element1 | | | | -----------| |----------- | | -----------| |----------- | | |element2 \ / | | | |element2 | | | | | ------------------------- | | ------------------------- | | Event CAPTURING | | Event BUBBLING | ----------------------------------- ----------------------------------- 首先发生捕获阶段,然后是冒泡阶段。当您使用常规 DOM api 注册事件时,默认情况下事件将成为冒泡阶段的一部分,但这可以在事件创建时指定 // CAPTURING event button.addEventListener('click', handleClick, true) // BUBBLING events button.addEventListener('click', handleClick, false) button.addEventListener('click', handleClick) 在React中,冒泡事件也是你默认使用的。 // handleClick is a BUBBLING (synthetic) event <button onClick={handleClick}></button> // handleClick is a CAPTURING (synthetic) event <button onClickCapture={handleClick}></button> 让我们看一下handleClick回调(React): function handleClick(e) { // This will prevent any synthetic events from firing after this one e.stopPropagation() } function handleClick(e) { // This will set e.defaultPrevented to true // (for all synthetic events firing after this one) e.preventDefault() } 我在这里没有看到提到的替代方案 如果您在所有事件中调用 e.preventDefault(),您可以检查事件是否已被处理,并防止再次处理它: handleEvent(e) { if (e.defaultPrevented) return // Exits here if event has been handled e.preventDefault() // Perform whatever you need to here. } 关于合成事件和原生事件的区别,请参阅React文档:https://reactjs.org/docs/events.html 这是防止单击事件前进到下一个组件然后调用 yourFunction 的简单方法。 <Button onClick={(e)=> {e.stopPropagation(); yourFunction(someParam)}}>Delete</Button> 这不是 100% 理想,但如果在儿童中传递 props 太痛苦 -> 儿童时尚或为此目的创建 Context.Provider/Context.Consumer just),你正在处理另一个库,它有自己的处理程序,它在您的处理程序之前运行,您也可以尝试: function myHandler(e) { e.persist(); e.nativeEvent.stopImmediatePropagation(); e.stopPropagation(); } 据我了解,event.persist方法可以防止对象立即被扔回React的SyntheticEvent池中。因此,当你伸手去拿 React 中传递的 event 时,它实际上并不存在!这种情况发生在孙子中,因为 React 在内部处理事情的方式是首先检查父进程是否有 SyntheticEvent 处理程序(特别是如果父进程有回调)。 只要您不调用 persist 来创建大量内存以继续创建诸如 onMouseMove 之类的事件(并且您没有创建某种 Cookie Clicker 游戏,例如 Grandma's Cookies),就应该完全没问题! 另请注意:偶尔阅读他们的 GitHub,我们应该密切关注 React 的未来版本,因为他们可能最终会解决一些问题,因为他们似乎打算在编译器中折叠 React 代码/转译器。 如果您希望发生嵌套元素中的操作而不是父元素中的操作,那么,您可以从父元素的操作处理程序中检查目标的类型,然后基于该类型执行操作,即,如果目标是我们的嵌套元素,我们什么也不做。否则两个处理程序都会被调用。 // Handler of the parent element. Let's assume the nested element is a checkbox function handleSingleSelection(e) { if(e.target.type !== 'checkbox') { // We do not do anything from the // parent handler if the target is a checkbox ( our nested element) // Note that the target will always be the nested element dispatch(lineSelectionSingle({ line })) } } 我在 event.stopPropagation() 工作时遇到问题。如果您也这样做,请尝试将其移动到单击处理程序函数的顶部,这就是我需要做的来阻止事件冒泡。示例函数: toggleFilter(e) { e.stopPropagation(); // If moved to the end of the function, will not work let target = e.target; let i = 10; // Sanity breaker while(true) { if (--i === 0) { return; } if (target.classList.contains("filter")) { target.classList.toggle("active"); break; } target = target.parentNode; } } 您可以通过检查事件目标来避免事件冒泡。 例如,如果您将输入嵌套到 div 元素,其中有单击事件的处理程序,并且您不想处理它,则单击输入时,您可以将 event.target 传递到您的处理程序中,并检查处理程序应该是根据目标的属性执行。 例如,您可以检查 if (target.localName === "input") { return}。 所以,这是一种“避免”处理程序执行的方法 解决此问题的另一种方法可能是在子级上设置 onMouseEnter 和 onMouseLeave 事件。 (您的 < li > 标签) 每当鼠标悬停在子级上时,您都可以设置一个特定的状态,以阻止父级执行 onClick 函数内容。 比如: class List extends React.Component { constructor(props) { super(props) this.state.overLi = false } handleClick() { // do something } render() { return ( <ul onClick={(e) => { if (!this.state.overLi) { console.log("parent") this.handleClick() } }} > <li onClick={(e) => { console.log("child") // prevent default? prevent propagation? this.handleClick() }} onMouseEnter={() => this.setState({ overLi: true, }) } onMouseLeave={() => this.setState({ overLi: false, })} ></li> </ul> ) } } 我进行了很多搜索,但没有设法使用 e.stopPropagation() 为我的上下文实现任何解决方案 您可以验证点击的元素是否是预期的元素。 例如: class List extends React.Component { constructor(props) { super(props); } handleClick(e) { if(e.target.className==='class-name'){ // do something } } render() { return ( <ul {/* Replace this with handleClick */} onClick={(e) => { console.log('parent'); this.handleClick(); }} <li onClick={(e) => { console.log('child'); // prevent default? prevent propagation? this.handleClick(); }} </li> </ul> ) } } 执行此操作的新方法更加简单,并且会节省您一些时间!只需将事件传递到原始点击处理程序并调用 preventDefault();。 clickHandler(e){ e.preventDefault(); //Your functionality here }


© www.soinside.com 2019 - 2024. All rights reserved.