有什么方法可以将数据从组件状态发送到HoC?
我的组件
import React, { Component } from 'react';
import withHandleError from './withHandleError';
class SendScreen extends Component {
contructor() {
super();
this.state = {
error: true
}
}
render() {
return (
<div> Test </div>
)
}
};
export default withHandleError(SendScreen)
我的HoC组件:
import React, { Component } from 'react';
import { ErrorScreen } from '../../ErrorScreen';
import { View } from 'react-native';
export default Cmp => {
return class extends Component {
render() {
const { ...rest } = this.props;
console.log(this.state.error) //// Cannot read property 'error' of null
if (error) {
return <ErrorScreen />
}
return <Cmp { ...rest } />
}
}
}
有没有办法做到这一点?
唯一的选择是提供必须从外部进入SendScreen组件的道具吗?
答案 0 :(得分:0)
import React, { Component } from 'react';
import withHandleError from './withHandleError';
class SendScreen extends Component {
contructor() {
super();
this.state = {
error: true
}
}
render() {
return (
<div state={...this.state}> Test </div>
)
}
};
export default withHandleError(SendScreen)
您可以在组件中传递状态作为道具。
答案 1 :(得分:0)
父母不知道孩子的状态。尽管它可以获取具有引用并访问spark.sparkContext
.parallelize(dataSet)
.saveToPhoenix(
"\"tablename\"",
Seq("PK", "col1", "col2", "col3"),
zkUrl = Some("header1:2181}")
)
的孩子的实例,但它无法监视状态更新,但这样做的必要性表明存在设计问题。
lifting up the state就是这种情况。需要通知父母有错误:
state
答案 2 :(得分:0)
export default withHandleError(data)(SendScreen)
在数据中,您可以将要传递的值发送到HOC,并可以按需访问。
答案 3 :(得分:0)
我知道我回答晚了,但是我的回答可以帮助其他人
这很容易做到。
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import HocComponent from './HocComponent';
const propTypes = {
passToHOC: PropTypes.func,
};
class WrappedComponent extends Component {
constructor(props) {
super(props);
this.state = {
error: true,
};
}
componentDidMount() {
const {passToHOC} = this.props;
const {error} = this.state;
passToHOC(error); // <--- pass the <<error>> to the HOC component
}
render() {
return <div> Test </div>;
}
}
WrappedComponent.propTypes = propTypes;
export default HocComponent(WrappedComponent);
import React, {Component} from 'react';
export default WrappedComponent => {
return class extends Component {
constructor() {
super();
this.state = {
error: false,
};
}
doAnything = error => {
console.log(error); //<-- <<error === true>> from child component
this.setState({error});
};
render() {
const {error} = this.state;
if (error) {
return <div> ***error*** passed successfully</div>;
}
return <WrappedComponent {...this.props} passToHOC={this.doAnything} />;
}
};
};