简体   繁体   English

在 react native 中将 class 组件转换为钩子形式

[英]Converting class components to hooks form in react native

Not sure how I would convert this class component to hooks form.不知道如何将此 class 组件转换为挂钩形式。 I tried to, but the app doesn't run the same.我试过了,但应用程序运行不一样。 Here's the original code written as class components-这是编写为 class 组件的原始代码-

  class Area extends React.PureComponent {
  state = {
    data: [],
    tooltipX: null,
    tooltipY: null,
    tooltipIndex: null,
  };

  componentDidMount() {
    this.reorderData();
  }

  reorderData = () => {
    const reorderedData = DATA.sort((a, b) => {
      // Turn your strings into dates, and then subtract them
      // to get a value that is either negative, positive, or zero.
      return new Date(a.date) - new Date(b.date);
    });

    this.setState({
      data: reorderedData,
    });
  };

  render() {
    const { data, tooltipX, tooltipY, tooltipIndex } = this.state;
    const contentInset = { left: 10, right: 10, top: 10, bottom: 7 };

    const ChartPoints = ({ x, y, color }) =>
      data.map((item, index) => (
        <Circle
          key={index}
          cx={x(moment(item.date))}
          cy={y(item.score)}
          r={6}
          stroke={color}
          fill="white"
          onPress={() =>
            this.setState({
              tooltipX: moment(item.date),
              tooltipY: item.score,
              tooltipIndex: index,
            })
          }
        />
      ));

    return (
      <SafeAreaView style={{ flex: 1 }}>
        <View style={styles.container}>
          {data.length !== 0 ? (
            <AreaChart
              style={{ height: '70%' }}
              data={data}
              yAccessor={({ item }) => item.score}
              xAccessor={({ item }) => moment(item.date)}
              contentInset={contentInset}
              svg={{ fill: '#003F5A' }}
              numberOfTicks={10}
              yMin={0}
              yMax={10}
            >
              <Grid svg={{ stroke: 'rgba(151, 151, 151, 0.09)' }} belowChart={false} />
              <ChartPoints color="#003F5A" />
              <Tooltip
                tooltipX={tooltipX}
                tooltipY={tooltipY}
                color="#003F5A"
                index={tooltipIndex}
                dataLength={data.length}
              />
            </AreaChart>
          ) : (
            <View
              style={{
                height: '50%',
                justifyContent: 'center',
                alignItems: 'center',
              }}
            >
              <Text
                style={{
                  fontSize: 18,
                  color: '#ccc',
                }}
              >
                There are no responses for this month.
              </Text>
            </View>
          )}
          <Text style={styles.heading}>Tooltip Area Chart</Text>
        </View>
      </SafeAreaView>
    );
  }
} 

This code is being used to integrate tooltip in react native charts.此代码用于将工具提示集成到反应原生图表中。 I want to include this code with rest of the project code written in hooks form.我想将此代码包含在以钩子形式编写的项目代码的 rest 中。

  export default class myPureComponent extends React.PureComponent

is equal to:等于:

export default React.memo(()=>{
   return <View>//...</view>
},(prevProps, nextProps) => {
  return prevProps.x === nextProps.x;
  // the component will be updated only on `x` prop changes.
})

componentDidMount is equal to: componentDidMount等于:

React.useEffect(()=>reorderData(),[]);

Try to format your codes properly.尝试正确格式化您的代码。

Add a [] in your use effects to it only render once.在您的使用效果中添加一个 [] 以使其仅呈现一次。

    useEffect(() => {
      reorderData();
    },[]);   //add [] as a dependency, this renders useEffect only on mount.

Full codes完整代码

const Area = () => {
const [ data, setData ] = useState([]);
const [ tooltipX, setTooltipX ] = useState(null);
const [ tooltipY, setTooltipY ] = useState(null);
const [ tooltipIndex, setTooltipIndex ] = useState(null);

useEffect(() => reorderData(),[]);

const reorderData = () => {
    const reorderedData = DATA.sort((a, b) => {
      // Turn your strings into dates, and then subtract them
      // to get a value that is either negative, positive, or zero.
      return new Date(a.date) - new Date(b.date);
    });
    
    setData(reorderedData);
  };

 const contentInset = { left: 10, right: 10, top: 10, bottom: 7 };
 
 const ChartPoints = ({ x, y, color }) =>
      data.map((item, index) => (
        <Circle
          key={index}
          cx={x(moment(item.date))}
          cy={y(item.score)}
          r={6}
          stroke={color}
          fill="white"
          onPress={() =>
            this.setState({
              tooltipX: moment(item.date),
              tooltipY: item.score,
              tooltipIndex: index,
            })
          }
        />
      ));

    return (
      <SafeAreaView style={{ flex: 1 }}>
        <View style={styles.container}>
          {data.length !== 0 ? (
            <AreaChart
              style={{ height: '70%' }}
              data={data}
              yAccessor={({ item }) => item.score}
              xAccessor={({ item }) => moment(item.date)}
              contentInset={contentInset}
              svg={{ fill: '#003F5A' }}
              numberOfTicks={10}
              yMin={0}
              yMax={10}
            >
              <Grid svg={{ stroke: 'rgba(151, 151, 151, 0.09)' }} belowChart={false} />
              <ChartPoints color="#003F5A" />
              <Tooltip
                tooltipX={tooltipX}
                tooltipY={tooltipY}
                color="#003F5A"
                index={tooltipIndex}
                dataLength={data.length}
              />
            </AreaChart>
          ) : (
            <View
              style={{
                height: '50%',
                justifyContent: 'center',
                alignItems: 'center',
              }}
            >
              <Text
                style={{
                  fontSize: 18,
                  color: '#ccc',
                }}
              >
                There are no responses for this month.
              </Text>
            </View>
          )}
          <Text style={styles.heading}>Tooltip Area Chart</Text>
        </View>
      </SafeAreaView>
    );
  
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM