基本上,我有一个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());
} …Run Code Online (Sandbox Code Playgroud) javascript reactjs redux react-redux higher-order-components
最近有消息称 React 很快就会被弃用componentWillReceiveProps,取而代之的是新的静态函数getDerivedStateFromProps。在这里查看更多内容
getDerivedStateFromProps我目前正在将我的应用程序迁移到这个新的 API,但由于我正在将重构库用于更高阶的组件,所以我遇到了问题。componentWillReceive我们通过库的生命周期对象来使用props。
所以在转向新的 API 之前,我有以下内容:
export function someHoC () {
return compose(
lifecycle({
componentWillReceiveProps (nextProps) {
const { fetch } = nextProps
if (shouldFetch(this.props, nextProps)) {
fetch()
}
}
})
)
}
Run Code Online (Sandbox Code Playgroud)
现在已更改为以下内容:
export function someHoC () {
return compose(
lifecycle({
getDerivedStateFromProps (nextProps) {
const { fetch } = nextProps
if (shouldFetch(this.props, nextProps)) {
fetch()
}
}
})
)
}
Run Code Online (Sandbox Code Playgroud)
但是,getDerivedStateFromProps需要是静态的,所以我收到了有关此问题的警告,并且不知道如何处理它。
warning.js?7f205b4:33 警告:lifecycle(MyComponent):getDerivedStateFromProps() 被定义为实例方法,将被忽略。相反,将其声明为静态方法。
我该怎么做才能将它作为静态生命周期方法传递到我的组件中?
我正在写一个 HOC 来反应来处理一些滚动功能的繁重工作。我很难让组件渲染。我不断收到此错误:
warning.js?d9a2:33 Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: object.
Run Code Online (Sandbox Code Playgroud)
我将其精简为 HOC 的最基本部分,但仍然收到此错误。这是我的代码:
这是 HOC 本身:
warning.js?d9a2:33 Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: object.
Run Code Online (Sandbox Code Playgroud)
这就是我在我的观点之一中使用它的方式:
import React from 'react';
const withOnScreenMonitor = WrappedComponent => {
return class OnScreenMonitor extends React.Component {
render(){
return (
<WrappedComponent/>
)
}
}
};
export default …Run Code Online (Sandbox Code Playgroud)我正在使用带有 TypeScript 的 React Native。我写了一个 HOC,我喜欢用它作为装饰器来给组件一个徽章:
import React, { Component, ComponentClass, ReactNode } from "react";
import { Badge, BadgeProps } from "../Badge";
function withBadge<P>(
value: number,
hidden: boolean = value === 0
): (WrappedComponent: ComponentClass<P>) => ReactNode {
return (WrappedComponent: ComponentClass<P>) =>
class BadgedComponent extends Component<P> {
render() {
return (
<React.Fragment>
<WrappedComponent {...this.props} />
{!hidden && <Badge value={value} />}
</React.Fragment>
);
}
};
}
export default withBadge;
Run Code Online (Sandbox Code Playgroud)
现在的问题是,当我尝试将此组件用作这样的装饰器时:
import React, { PureComponent } from "react";
import { Icon } …Run Code Online (Sandbox Code Playgroud) typescript reactjs typescript-typings typescript-types higher-order-components
IFoo我正在尝试编写一个通用的 React 组件,它需要两种类型(或)之一的 propsIBar以及接受所选类型的 props 的组件。
为什么下面的不起作用?
import React from 'react';
interface IFoo {
x: string;
}
interface IBar {
x: number;
}
const foo: React.FunctionComponent<IFoo> = (props: IFoo) => {
console.log("hello from foo!");
return <div>foo</div>
};
const bar: React.FunctionComponent<IBar> = (props: IBar) => {
console.log("hello from bar!");
return <div>bar</div>
};
interface IProps<T> {
props: T[];
Component: React.FunctionComponent<T>;
}
class HigherOrderComponent<T extends IBar | IFoo> extends React.Component<IProps<T>> {
render() {
const { props, Component } = …Run Code Online (Sandbox Code Playgroud) 我想向 Next.js 应用程序的某些页面添加持久布局。我发现这篇文章解释了人们如何做到这一点的几种方法。看起来很简单,但是在使用推荐的方法时我遇到了以下两个问题:
as any:const getLayout =
(Component as any).getLayout ||
((page: NextPage) => <SiteLayout children={page} />);
Run Code Online (Sandbox Code Playgroud)
withApolloHOC(来自此处)。使用这个会导致Component.getLayout总是undefined。我对正在发生的事情没有足够的了解来知道为什么会发生这种情况(我可以猜到),所以我自己很难解决这个问题。我正在使用react-speech-recognition在我的 React 应用程序中将语音转录为文本。react-speech-recognition 提供了SpeechRecognition高阶组件,它注入了额外的属性,比如browserSupportsSpeechRecognition被封装的组件。
我的 App 组件如下所示:
// src/App.js
import React, { useEffect } from 'react';
import SpeechRecognition from 'react-speech-recognition';
const App = ({ transcript, browserSupportsSpeechRecognition }) => {
useEffect(() => {
console.log(`transcript changed: ${transcript}`);
}, [transcript]);
if (! browserSupportsSpeechRecognition) {
return <span className="error">Speech recognition not supported</span>;
}
return <span className="transcript">{transcript}</span>;
};
const options = {
autoStart: false,
continuous: false
};
export default SpeechRecognition(options)(App);
Run Code Online (Sandbox Code Playgroud)
我编写了一些测试来模拟支持语音识别的浏览器和不支持语音识别的浏览器:
// src/App.spec.js
import React from 'react';
import Enzyme, { …Run Code Online (Sandbox Code Playgroud) JSFiddle:https ://jsfiddle.net/40vpaLj5/
我用谷歌搜索了一些问题,我发现唯一消失的相关问题是当人们在模态上使用它时,他们谈到设置 z-index 来修复它。反正我试过了还是什么都没有。我怎样才能解决这个问题?
import React from 'react';
import PlaylistPages from './PlaylistPages';
class PlaylistSortableComponent extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
test: [
'1','2', '3', '4'
]
}
}
render() {
return (
<PlaylistPages pages={this.state.test} style={{zIndex: 999999}} />
);
}
}
const PlaylistPages = SortableContainer(({pages}) => {
return (
<div>
{
pages.map((page, index) =>
<PlaylistPage key={index} page={page} style={{zIndex: 99999999}} />
)}
</div>
);
});
const PlaylistPage = SortableElement(({page}) => {
return (
<div style={{zIndex: …Run Code Online (Sandbox Code Playgroud) javascript drag-and-drop reactjs higher-order-components react-sortable-hoc
我在使用 TypeScript 书学习 React 进行编码时碰壁了。我投降了,直接从书上复制粘贴的代码,但是编译器还是不爽
我目前的解决方法是提供“任何”值,而不是 IProps,但这是一个廉价的黑客。
不工作的代码:
import * as React from 'react';
interface IProps {
loading: boolean;
}
const withLoader = <P extends object>(
Component: React.ComponentType<P>
): React.FunctionComponent<P & IProps> => ({ loading, ...props }:
IProps) =>
loading ? (
<div className="loader-overlay">
<div className="loader-circle-wrap">
<div className="loader-circle" />
</div>
</div>
) : (
<Component {...props} />
);
export default withLoader;
Run Code Online (Sandbox Code Playgroud)
工作代码(我只将 IProps 更改为 any):
import * as React from 'react';
interface IProps {
loading: boolean;
}
const withLoader = …Run Code Online (Sandbox Code Playgroud) types typescript reactjs higher-order-components react-props
我正在学习 HOC 并继续阅读上面的引文,但我不明白它的意思。如果我的 HOC 向我的消费组件添加了一个方法,我可以像这样在渲染方法中使用该方法吗?如果不是,我将如何做我在这里想做的事情:
import React, { Component } from 'react';
import { withMyHOC } from '../with_my_component'
class MyComponent extends Component {
constructor(props) {
super(props);
}
render() {
const { methodFromHOC }= this.props;
const result = methodFromHOC(someArgument);
return (
<div >
{result}
</div>
)
}
}
export default withMyHOC(MyComponent );
Run Code Online (Sandbox Code Playgroud) reactjs ×10
typescript ×4
javascript ×3
enzyme ×1
html ×1
jestjs ×1
next.js ×1
react-props ×1
react-redux ×1
recompose ×1
redux ×1
types ×1