Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have the following code in a component and I would like a stateless component to access this part of code:

Main component:

function createApp(store, communityIds) {
const App = React.createClass({

    childContextTypes: {
        localizedString: React.PropTypes.func,
    },

    getChildContext: function() {
        return {
            localizedString: function(key, fallback) {
                return getKey(key, fallback);
            },
        };
    },

    render: function() {
        return (
            <Provider store={store}>
                <Client communityIds={communityIds}/>
            </Provider>
        );
    },
});

return <App/>;
}

Stateless:

export default () => (dispatch, getState) => {
    const state = getState();

    const token = state.user.get('token');

    if (!token) {
        throw new Error('test'); // this.context.localizedString does not work
    }
}
question from:https://stackoverflow.com/questions/35866066/context-in-stateless-component

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
170 views
Welcome To Ask or Share your Answers For Others

1 Answer

What you have provided under your definition of "Stateless:" function is not what a Stateless function is. You have provided your action creator as a thunk. I assume you wanted to insert the code for your Client component instead. To access context in a stateless component, your Client component would do something like this (which is documented here)

const Client = (props, context) => {   
    return  <div >{context.localizedString("someKey", "someFallback")} </div>
}

Client.contextTypes = {
    localizedString: React.PropTypes.func
}

export default Client

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...