You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin Multiplatform JS React中如何使用Redux Store Provider?

Kotlin Multiplatform/JS 与 React-Redux 配置方式更新说明

在Kotlin Multiplatform/JS结合React-Redux开发时,某版本发布后,旧的Redux Store Provider配置方式已被弃用(仅能在kotlin-react-legacy库中正常使用)。由于官方缺少相关文档和代码示例,新配置方式的上手难度较高。

旧版弃用的实现方式

import react.dom.render
import react.router.dom.*
import react.redux.provider
import react.RBuilder
import redux.createStore
import redux.rEnhancer
import kotlinx.browser.document

fun main() {
    val rootDiv = document.getElementById("root")!!
    render(rootDiv) {
        provider(store) { // 此写法已被弃用
            app()
        }
    }
}

fun RBuilder.App() = { ... }

val store = createStore(::reducer, 0, rEnhancer())

fun reducer(state: Int = 0, action: Any): Int {
    return when (action) {
        is Increment -> state + 1
        is Decrement -> state - 1
        else -> state
    }
}

class Increment : RAction
class Decrement : RAction

新版正确实现方式

新版需要在provider的lambda代码块内通过赋值store属性来关联Redux Store,具体代码如下:

import react.dom.render
import react.router.dom.*
import react.redux.provider
import react.RBuilder
import redux.createStore
import redux.rEnhancer
import kotlinx.browser.document

fun main() {
    val rootDiv = document.getElementById("root")!!
    render(rootDiv) {
        provider {
            // 在lambda块内指定Redux Store
            store = this@main.store
            app()
        }
    }
}

fun RBuilder.app() = component {
    // 组件内部逻辑,可通过useSelector、useDispatch等API访问Store
}

val store = createStore(::reducer, 0, rEnhancer())

fun reducer(state: Int = 0, action: Any): Int {
    return when (action) {
        is Increment -> state + 1
        is Decrement -> state - 1
        else -> state
    }
}

class Increment : RAction
class Decrement : RAction

关键变更说明

  • 旧版直接将store作为provider函数参数传入的写法已被移除,需改为在provider的lambda块内赋值store属性
  • 组件内部仍可通过useSelector、useDispatch等React-Redux Hooks API与Store交互,用法与之前一致

内容的提问来源于stack exchange,提问作者Mr. Goldberg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 15:42:53