在实现像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>
)
}
}
如果单击该按钮,则在完成服务器请求后,将更新状态并触发警报。在某些模态和警报库中使用这样的ref很常见。
现在,在Redux(或任何Flux实现)中,fetch()将存在于一个单独的文件中,该文件无法访问this._alert
。
在不重写外部“警报”库的情况下维护功能的最佳方法是什么?
答案 0 :(得分:7)
作为备注,我来自您的帖子:https://dannyherran.com/2017/03/react-redux-mobx-takeaways/
这从一开始就是错误的。不应在组件之间共享参考,因为它们将它们耦合在一起。组件应设计成完全彼此分离,并根据给定的状态做出反应。
问题在于裁判没有告诉你组件本身的状态,你不知道它是否已经安装,你不知道它是否存在,所以你正在玩不稳定的东西。
因此,让我们将所有内容分离并正确利用react / redux的强大功能,所有代码应以这种方式组织:
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;
}
调整警报显示设置的操作,以及执行提取并生成正确结果的异步操作。
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))
});
}
}
连接组件。不需要共享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);
答案 1 :(得分:2)
首先,您是否尝试在handleClick中使用箭头功能?
handleClick() {
fetch('api').then(() => {
this.setState({ clicked: true });
this._alert.show('Cool response!');
});
}
这可能会影响this
另一方面,如果使用Redux,则应创建两个操作。
例如,fetchAPI()
和APIfetched()
。