Skip to content

PreAction for React Component

Fred Chien edited this page Oct 31, 2015 · 2 revisions

React Component requires initial state to render page and content correctly. There are many way to make it works but not all of them works for isomorphic. Lantern provided a way to pre-fetch data before React component rendering, and it works on client and server both.

Pre-Action Decorator

@preAction decorator is used to do some works to get states which is required by React Component.

First, you have to load decorator:

import { preAction } from 'Decorator';

Attach it to class:

@preAction('Chatroom.fetchMessages')
class MyComponent extends React.Component {
    // ...
}

In the example above, it will call action.Chatroom.fetchMessages with FLUX framework to prepare state for Chatroom store. Then React Component can use current initial state for rendering.

More actions and Call with Parameters

You might need to call more than one actions and call with parameters. It allows passing function to @preAction decorator to do more complicated works.

@preAction((handle) => {
    handle.doAction('Chatroom.setNickName', 'Guest');
    handle.doAction('Chatroom.setGender', 'Male');
})

Using Properties of React Component

Using properties of React Component is possible with handle object.

@preAction((handle) => {
    handle.doAction('Chatroom.setNickName', handle.props.name);
})