将数据从HTML获取到React/Redux

Ste*_*che 1 reactjs redux react-redux

我的后端服务器正在呈现一个HTML页面,其中包含javascript对象中的一些数据以及React/Redux应用程序使用的根元素:

<script>
MY_DATA = {
    foo: 'bar'
}
</script>

<div id="app"></div>
Run Code Online (Sandbox Code Playgroud)

我需要以某种方式MY_DATA从HTML到我的redux商店.我尝试使用我的React根元素的componentDidMount从窗口对象中提取数据,但这不起作用.

有一个更好的方法吗?

QoP*_*QoP 6

从窗口中获取初始状态并将其传递给createStore.它在这里解释(客户端部分)

const initialState = window.MY_DATA

// Create Redux store with initial state
const store = createStore(yourApp, initialState)

render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('app')
)
Run Code Online (Sandbox Code Playgroud)