2016-03-08 59 views
12

我有下面的代碼中的組成部分,我想一個無狀態的組件來訪問這部分代碼:「無狀態」組件中的上下文?

主要成份:

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/>; 
} 

無狀態:

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 
} 
} 

希望任何提示,問候!

回答

14

您在「無狀態:」函數定義下提供的內容不是無狀態函數。你已經爲你的動作創造者提供了一個thunk。我假設你想爲你的客戶端組件代替插入代碼。要訪問上下文一個無狀態組件,您的客戶端組件會做這樣的事情(這是記錄here

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

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

export default Client 
1

另一種解決方案是自調用函數:

export default (Component=>(
    Component.contextTypes = { 
    localizedString: React.PropTypes.func 
    }) && Component 
)((props, context)=>{ 
    return <div>{context.localizedString("someKey", "someFallback")}</div> 
}) 

或者,如果你定義contextTypes分開重複使用它,你可以這樣做:

//addContextTypes.js 
export default function(Component){ 
    return (Component.contextTypes = { 
    localizedString: React.PropTypes.func 
    }) && Component 
} 

//component.jsx 
import addContextTypes from './addContextTypes' 
export default addContextTypes((props, context)=>{ 
    return <div>{context.localizedString("someKey", "someFallback")}</div> 
})