cla*_*ccs 4 javascript reactjs redux react-redux higher-order-components
基本上,我有一个AuthenticationHOC必须获取 redux 状态,检查令牌是否存在,如果存在,则呈现包装的组件。如果没有,则调度一个动作来尝试从 localStorage 加载令牌。如果失败,请重定向到登录页面。
import React from 'react';
import { connect } from 'react-redux';
import * as UserActions from '../../state/actions/user-actions';
import * as DashboardActions from '../../state/actions/dashboard-actions';
const mapStateToProps = state => {
return {
token: state.user.token,
tried: state.user.triedLoadFromStorage,
};
};
const _AuthenticationHOC = Component => props => {
// if user is not logged and we 've not checked the localStorage
if (!props.token && !props.tried) {
// try load the data from local storage
props.dispatch(DashboardActions.getDashboardFromStorage());
props.dispatch(UserActions.getUserFromStorage());
} else {
// if the user has not token or we tried to load from localStorage
//without luck, then redirect to /login
props.history.push('/login');
}
// if the user has token render the component
return <Component />;
};
const AuthenticationHOC = connect(mapStateToProps)(_AuthenticationHOC);
export default AuthenticationHOC;
Run Code Online (Sandbox Code Playgroud)
然后我尝试像这样使用它
const SomeComponent = AuthenticationHOC(connect(mapStateToProps)(HomeComponent));
Run Code Online (Sandbox Code Playgroud)
但我总是收到一个错误,准确标记了上面的行。
类型错误:Object(...) 不是函数
然后我做了一个简化版
我将 HOC 中的代码替换为最简单的版本
const _AuthenticationHOC = Component => props => {
return <Component {...props}/>;
};
Run Code Online (Sandbox Code Playgroud)
这也不起作用。然后我从我的 HOC 中删除了连接功能,然后只导出这个组件和 tada!...现在工作!
所以我怀疑 connect 返回了一个不能用作 HoC 函数的对象。这样对吗?我能在这里做什么?
Emi*_*ron 15
请参阅此答案的底部以阅读对问题内容的直接回复。我将从我们在日常开发中使用的良好实践开始。
Redux 提供了一个有用的compose实用函数。
所有
compose所做的就是让你写深度嵌套函数变换无码的向右漂移。
因此,在这里,我们可以使用它以可读的方式嵌套 HoC。
// Returns a new HoC (function taking a component as a parameter)
export default compose(
// Parent HoC feeds the Auth HoC
connect(({ user: { token, triedLoadFromStorage: tried } }) => ({
token,
tried
})),
// Your own HoC
AuthenticationHOC
);
Run Code Online (Sandbox Code Playgroud)
这类似于手动创建一个新的容器 HoC 函数。
const mapState = ({ user: { token, triedLoadFromStorage: tried } }) => ({
token,
tried
});
export default WrappedComponent => connect(mapState)(
AuthenticationHOC(WrappedComponent)
);
Run Code Online (Sandbox Code Playgroud)
然后,您可以透明地使用您的 auth HoC。
import withAuth from '../AuthenticationHOC';
// ...
export default withAuth(ComponentNeedingAuth);
Run Code Online (Sandbox Code Playgroud)
为了将 auth 组件与存储和路由隔离,我们可以将其拆分为多个文件,每个文件都有自己的职责。
- withAuth/
- index.js // Wiring and exporting (container component)
- withAuth.jsx // Defining the presentational logic
- withAuth.test.jsx // Testing the logic
Run Code Online (Sandbox Code Playgroud)
我们让withAuth.jsx文件专注于渲染和逻辑,无论它来自哪里。
// withAuth/withAuth.jsx
import React from 'react';
export default Component => ({
// Destructure props here, which filters them at the same time.
tried,
token,
getDashboardFromStorage,
getUserFromStorage,
onUnauthenticated,
...props
}) => {
// if user is not logged and we 've not checked the localStorage
if (!token && !tried) {
// try load the data from local storage
getDashboardFromStorage();
getUserFromStorage();
} else {
// if the user has no token or we tried to load from localStorage
onUnauthenticated();
}
// if the user has token render the component PASSING DOWN the props.
return <Component {...props} />;
};
Run Code Online (Sandbox Code Playgroud)
看?我们的 HoC 现在不知道存储和路由逻辑。我们可以将重定向移动到商店中间件或其他任何地方,<Component onUnauthenticated={() => console.log('No token!')} />如果商店不是您想要的地方,它甚至可以在道具中进行自定义。
然后,我们只在 中提供 props index.js,就像一个容器组件。1
// withAuth/index.js
import React from 'react';
import { connect } from 'react-redux';
import { compose } from 'redux';
import { getDashboardFromStorage, onUnauthenticated } from '../actions/user-actions';
import { getUserFromStorage } from '../actions/dashboard-actions';
import withAuth from './withAuth';
export default compose(
connect(({ user: { token, triedLoadFromStorage: tried } }) => ({
token,
tried
}), {
// provide only needed actions, then no `dispatch` prop is passed down.
getDashboardFromStorage,
getUserFromStorage,
// create a new action for the user so that your reducers can react to
// not being authenticated
onUnauthenticated,
}),
withAuth
);
Run Code Online (Sandbox Code Playgroud)
具有onUnauthenticated作为存储操作的好处是不同的减速器现在可以对其做出反应,例如擦除用户数据、仪表板数据等。
然后,可以withAuth使用Jest和酶之类的东西来测试HoC的孤立逻辑。
// withAuth/withAuth.test.jsx
import React from 'react';
import { mount } from 'enzyme';
import withAuth from './withAuth';
describe('withAuth HoC', () => {
let WrappedComponent;
let onUnauthenticated;
beforeEach(() => {
WrappedComponent = jest.fn(() => null).mockName('WrappedComponent');
// mock the different functions to check if they were called or not.
onUnauthenticated = jest.fn().mockName('onUnauthenticated');
});
it('should call onUnauthenticated if blah blah', async () => {
const Component = withAuth(WrappedComponent);
await mount(
<Component
passThroughProp
onUnauthenticated={onUnauthenticated}
token={false}
tried
/>
);
expect(onUnauthenticated).toHaveBeenCalled();
// Make sure props on to the wrapped component are passed down
// to the original component, and that it is not polluted by the
// auth HoC's store props.
expect(WrappedComponent).toHaveBeenLastCalledWith({
passThroughProp: true
}, {});
});
});
Run Code Online (Sandbox Code Playgroud)
为不同的逻辑路径添加更多测试。
所以我怀疑它
connect返回一个不能用作 HoC 函数的对象。
react-reduxconnect返回一个 HoC。
Run Code Online (Sandbox Code Playgroud)import { login, logout } from './actionCreators' const mapState = state => state.user const mapDispatch = { login, logout } // first call: returns a hoc that you can use to wrap any component const connectUser = connect( mapState, mapDispatch ) // second call: returns the wrapper component with mergedProps // you may use the hoc to enable different components to get the same behavior const ConnectedUserLogin = connectUser(Login) const ConnectedUserProfile = connectUser(Profile)在大多数情况下,包装器函数将被立即调用,而不会保存在临时变量中:
Run Code Online (Sandbox Code Playgroud)export default connect(mapState, mapDispatch)(Login)
然后我尝试像这样使用它
Run Code Online (Sandbox Code Playgroud)AuthenticationHOC(connect(mapStateToProps)(HomeComponent))
虽然您连接 HoC 的顺序颠倒了,但您已经接近了。它应该是:
connect(mapStateToProps)(AuthenticationHOC(HomeComponent))
Run Code Online (Sandbox Code Playgroud)
这样,AuthenticationHOC从 store 接收 propsHomeComponent并被正确的 HoC 正确包装,这将返回一个新的有效组件。
话虽如此,我们可以做很多事情来改进这个 HoC!
1. 如果您不确定是否将index.js文件用于容器组件,您可以根据自己的喜好重构它,比如一个withAuthContainer.jsx文件,它要么在索引中导出,要么让开发人员选择他们需要的文件.
| 归档时间: |
|
| 查看次数: |
3502 次 |
| 最近记录: |