简体   繁体   中英

Compiling and serving React components individually

We are using Laravel Mix to compile react components and serve them individually to the respective pages where they are needed - It's not a SPA.

I'm new to React, so excuse my ignorance. I'm trying to get my head around the current setup and find out if it's the proper way of having multiple components in the same page.

So the boilerplate below has been copied and pasted in every component, only changing the selector, eg:

'use strict'
import React from 'react'
import ReactDOM from 'react-dom'
import {Provider} from 'react-redux'
import {createStore, applyMiddleware, compose} from 'redux'
import ReduxPromise from 'redux-promise'
import App from './containers/App'
import reducers from './reducers'

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose
const enhancer = composeEnhancers(
    applyMiddleware(ReduxPromise),
)
const newstore = createStore(reducers, enhancer)

ReactDOM.render(
    <Provider store={newstore}>
        <App />
    </Provider>, document.querySelector('.component-foo')
)

Some components also differ slightly in how the store is created, eg redux devtools is not always present.

So, coming from Vue.js, that doesn't make much sense to me - in Vue.js you'd use a single file to import everything related to the framework and then load each component you need with a single line of code. But this React setup seems to be doing quite the opposite: loading a separate instance of React and Redux for every component in the page, as if I had multiple root/app components in Vue.js.

Is it right to assume React is being bundled and booted multiple times and would that be the proper way to do things?

You're almost certainly doing this wrong. Yes, its very likely you are bundling and booting React multiple times, but no that is not the proper way to do things. It seems you are trying to use the Vue paradigm to do this but with code copied from a React SPA which is why you are building this monstrosity.

May I suggest checking basic react+laravel tutorials before you proceed? simple google search showed this: https://code.tutsplus.com/tutorials/build-a-react-app-with-laravel-backend-part-2-react--cms-29443 and I'm sure there are many others.

Since you are new to react, avoid redux for now and just get familiar with putting up react with multiple components. only then add the redux state management IF YOU NEED IT.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM