【问题标题】:Fluxible context and executeAction in child react components子反应组件中的可变上下文和 executeAction
【发布时间】:2015-06-22 16:32:06
【问题描述】:

使用FluxibleMixin,我可以按预期访问组件中的executeActiongetStore 方法。

使用没有 Mixins 的 ES6 样式组件类,我的顶级组件(在 react-router 下)按预期接收上下文,但对于子组件,我似乎必须明确要求组件上下文需求。

例如,在我的Application 组件下,我有以下内容:

import React from 'react';
import setUserName from '../actions/setUserName';
import UserStore from '../stores/ProfileStore';
import {provideContext} from 'fluxible/addons';

/**
 *
 */
class Home extends React.Component {

    constructor (props) {
        super(props);
        this.state = props.state;
    }

    handleClick (event) {
        context.getComponentContext().executeAction(setUserName, {name:this.state.name});
    }

    handleNameEntry (event) {
        this.setState({name:event.target.value});
    }

    render () {
        return (
            <div>
                <h1>Enter your name to start</h1>
                <input type="text" onChange={this.handleNameEntry.bind(this)} />
                <input type="button" value="Find me" onClick={this.handleClick.bind(this)} />
            </div>
        );
    }
}

export default Home;

这行得通,因为handleClick 方法成功调用了executeAction 方法,但我不确定这是否正确。

当我想使用上下文方法时,是否需要显式调用context.getComponentContext()

为什么context.executeAction 可以直接在父组件上使用,而这个却不行?

【问题讨论】:

    标签: javascript reactjs reactjs-flux flux


    【解决方案1】:

    只有在你使用 contextTypes 明确请求时,上下文成员才能直接在 React 类中使用:

    class Home extends React.Component {}
    
    Home.contextTypes = {
        getStore:      React.PropTypes.func.isRequired,
        executeAction: React.PropTypes.func.isRequired
    };
    

    之后,您将能够从组件内部执行 context.executeAction。您应该只在顶级组件上使用一次 provideContext。

    【讨论】:

    • 我以为我最初尝试过这个,但我想我一定也一直在尝试在子组件上provideContext,这似乎会导致问题。谢谢!
    猜你喜欢
    • 2021-01-06
    • 1970-01-01
    • 1970-01-01
    • 2020-12-17
    • 2021-08-07
    • 1970-01-01
    • 2021-08-21
    • 1970-01-01
    • 2020-01-01
    相关资源
    最近更新 更多