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

Dan*_*n H 4 javascript flux reactjs redux

在实现像Redux或MobX这样的状态容器时,通常会将状态和事件移动到不再能读取引用的单独类或对象.

例如,在正常组件中:

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>
    )
  }
}
Run Code Online (Sandbox Code Playgroud)

如果单击该按钮,则在完成服务器请求后,将更新状态并触发警报.在某些模态和警报库中使用这样的引用是很常见的.

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

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

小智 8

作为一个说明,我来自你的帖子:https://dannyherran.com/2017/03/react-redux-mobx-takeaways/

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

问题是,ref告诉你组件本身的状态,你不知道它是否已经安装,你不知道它是否存在,所以你正在玩一些不稳定的东西.

因此,让我们将所有内容分离并正确利用react/redux的功能,所有代码都应该以这种方式组织:

1.减速剂:

Reducer将保持警报的显示状态.整个应用程序中的任何组件现在都可以访问它,与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;
}
Run Code Online (Sandbox Code Playgroud)

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

    }

}
Run Code Online (Sandbox Code Playgroud)

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);
Run Code Online (Sandbox Code Playgroud)