简体   繁体   中英

How do I split up a large react component?

I'm learning react by programming the cardgame Solitaire. My main component, where I render the game board and the cards, has become very large (700 lines and growing).

The big bulk of that is all animation related and I would like to throw all the animation related methods into different files.

I'm not sure how to go about that in React. If I was doing this in Ruby, I would simply create a helper module, import the module and call the functions on the module. Creating a helper file and putting the functions in there doesn't seem to work in React, because I don't have access to "this" in those functions.

How would you deal with this situation in react? What patterns do people usually use when they want to separate out the logic in React components?

Edit 1 (added example component):

I've already read the React docs and I am already using Redux. My issue is that i have a lot of animations and UI moving around using JavaScript. Here's a link to the component I'm talking about:

https://gist.github.com/holgersindbaek/b8f134306148d12995dadf5e28d2d5b7

I'm keeping the current state of the game in the components "state". Once the Redux state changes, the props update and an animation is set off (move a card from old position "state" to new position "props". Once the animation is complete, the state of the component is updated so it's the same as the props.

My issue is that there's a lot of non-essential code in that component that's essentially just moving things around on the screen (initializeNewGame, initializeInteract, positionCardsOnBoard). How would you deal with such methods?

Edit 2 (I think I figured it out):

I've decided to place some of the animation functions in a helper file (animationHelper.js) and then import it in the React component and bind it to the component, so I can reference "this" in the animation function. I've updated the example to reflect the new changes:

https://gist.github.com/holgersindbaek/b8f134306148d12995dadf5e28d2d5b7

That seems like a good solution to me. Am I breaking any best practices by doing this?

I think you need something like Redux . Redux can help you keep your code scalable and maintainable. Basicaly, Redux allows you to split each component in two parts (or files), one for the view (components), and another for the busines logic (containers), which helps you test your code easely. Redux is a design pattern of unidirectional data flow.

In adition, you can apply some SOLID principles , applying Single Responsability for each component.

You can check an real example here .

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