React:如何从 Redux/Flux 操作访问组件引用?

React: How to access component refs from Redux/Flux actions?

在实现像 Redux 或 MobX 这样的状态容器时,您的状态和事件通常会移动到一个单独的 class 或对象,不再可以读取引用。

例如在普通组件中:

import Alert from Alert.js;

class Dummy extends React.Component {
  constructor(props) {
    super(props);

    this.state = { clicked: false }
  }

  handleClick() {
    fetch('api').then(function(){
      this.setState({ clicked: true });
      this._alert.show('Cool response!');
    });
  }

  render() {
    return (
      <div>
        <Alert ref={a => this._alert = a} />
        <Button onClick={this.handleClick}/>
      </div>
    )
  }
}

如果我单击该按钮,一旦服务器请求完成,就会更新状态并触发警报。像这样使用 refs 在一些模式和警报库中很常见。

现在,在 Redux(或任何 Flux 实现)中,fetch() 将存在于一个动作中,该动作存在于一个单独的文件中,该文件无权访问 this._alert.

在不重写外部 "Alert" 库的情况下维护功能的最佳方法是什么?

请注意,我来自您的 post:https://dannyherran.com/2017/03/react-redux-mobx-takeaways/

这从一开始就是错误的。 Refs 不应在组件之间共享,因为这会将它们耦合在一起。组件应该被设计成彼此完全解耦,并根据给定的状态做出反应。

问题是 ref 没有告诉您有关组件本身状态的任何信息,您不知道它是否已安装,甚至不知道它是否存在,所以您在玩弄一些不稳定的东西。

所以让我们解耦一切并适当地利用 react/redux 的力量,所有 代码应该以这种方式组织:

1。减速器:

Reducer 将保持警报的显示状态。 整个应用程序中的任何组件现在都可以访问它,独立 of refs,因此组件是否实际存在并不重要。

const DummyPageReducer = function(state, action) 
{
    if (state === undefined) 
    {
        state = 
        {
            alertShow: false
        };
    }

    switch(action.type) 
    {
        case 'ALERT_DISPLAY':
            return Object.assign({}, state, { alertShow: action.display });
    }
    return state;
}

2。动作和异步动作:

调整警报显示设置的操作,以及执行提取和生成正确结果的异步操作。

export const ALERT_DISPLAY = 'ALERT_DISPLAY '
export function alertDisplay(display) 
{
    return {
        type: ALERT_DISPLAY,
        display
    }
}

export function showAlert() 
{   
    return function (dispatch) 
    {  
        fetch('api').then(function()
        {
            dispatch(alertDisplay(true))
        });

    }

}

3。连通分量:

连接的组件。无需共享 refs,将使用 ref,但组件将对其给定的 props 做出反应并相应地设置 Alert。

import Alert from Alert.js;

class Dummy extends React.Component 
{
    constructor(props) 
    {
        super(props);

        this.setAlert = this.setAlert.bind(this);
    }

    setAlert()
    {
        if(this.props.alertShow)
            this._alert.show('Cool response!');
        else
            this._alert.hide();

    }

    componenDidMount()
    {
        setAlert();
    }

    componentDidUpdate(prevProps, prevState)
    {
        if(prevProps.alertShow !== this.props.alertShow)
            setAlert();
    }

    render() 
    {
        return 
        (
            <div>
                <Alert ref={a => this._alert = a} />
                <Button onClick={this.props.showAlert}/>
            </div>
        )
    }
}
Dummy = connect(

    state => 
    ({
        alertShow: state.Dummy.alertShow
    }),

    dispatch =>
    ({
        showAlert: () => dispatch(showAlert(true))
    })

)(Dummy);

首先,您尝试过在 handleClick 中使用箭头功能吗?

handleClick() {
    fetch('api').then(() => {
        this.setState({ clicked: true });
        this._alert.show('Cool response!');
    });
}

这可能会影响 this

的上下文

另一方面,如果你使用 Redux,你应该创建两个动作。 例如,fetchAPI()APIfetched().