【问题标题】:(React Native) How to Class to Function(React Native) 如何分类到函数
【发布时间】:2021-07-31 06:29:03
【问题描述】:

我的英语不是很好;我准备了一份申请。我想将以下 class 结构用作 functionconst。我怎样才能做到这一点?我想通过函数组件来使用props

我添加了整个代码。 年龄计算应用。

我使用了useState - useEffect,没有成功。

等待帮助我谢谢你

import React from "react";
import {
  StyleSheet,
  Text,
  View,
  Dimensions,
  Platform,
  TouchableOpacity,
} from "react-native";
import DateTimePicker from "react-native-modal-datetime-picker";

const { height } = Dimensions.get("window");

export default class App extends React.Component {
  state = {
    isDateTimePickerVisible: false,
    date: undefined,
  };

  _showDateTimePicker = () => this.setState({ isDateTimePickerVisible: true });

  _hideDateTimePicker = () => this.setState({ isDateTimePickerVisible: false });

  _handleDatePicked = (date) => {
    date = new Date(date);
    this.setState({ date: date }, () => {
      this._hideDateTimePicker();
      this._calculateTheDifference();
    });
  };
  _calculateTheDifference() {
    if (!this.state.date) {
      return;
    }
    let current_date = new Date().getDate();
    let current_month = new Date().getMonth();
    let current_year = new Date().getFullYear();
    let birth_date = this.state.date.getDate();
    let birth_month = this.state.date.getMonth();
    let birth_year = this.state.date.getFullYear();
    let month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    if (birth_date > current_date) {
      current_month = current_month - 1;
      current_date = current_date + month[birth_month - 1];
    }
    if (birth_month > current_month) {
      current_year = current_year - 1;
      current_month = current_month + 12;
    }
    let calculated_date = current_date - birth_date;
    let calculated_month = current_month - birth_month;
    let calculated_year = current_year - birth_year;
    if (calculated_date || calculated_month || calculated_year)
      this.setState({
        calculated_date: calculated_date,
        calculated_month: calculated_month,
        calculated_year: calculated_year,
        dateOpacity: 1,
      });
  }

  render() {
    return (
      <View style={styles.container}>
        <View style={styles.slider}>
          <View style={{ justifyContent: "center", alignItems: "center" }}>
            <Text style={styles.yasHesaplama}>Age Calculate</Text>
          </View>
        </View>
        <View style={{ flex: 1, backgroundColor: "#fff" }}>
          <View style={styles.solKose} />
          <View
            style={{
              flex: 1,
              backgroundColor: "#fff",
              borderTopLeftRadius: 65,
            }}
          />
        </View>
        <View style={styles.anaGovde}>
          <TouchableOpacity
            style={styles.touchableOpacity}
            onPress={this._showDateTimePicker}
          >
            <Text style={styles.dogumGunu}>Enter your birthday.</Text>
          </TouchableOpacity>
          <View style={[styles.viewText, { padding: 10 }]}>
            <Text style={styles.text}>
              {this.state.calculated_year}
              {" Year"}{" "}
            </Text>
            <Text style={styles.text}>
              {this.state.calculated_month}
              {" Month"}{" "}
            </Text>
            <Text style={styles.text}>
              {this.state.calculated_date}
              {" Date"}{" "}
            </Text>
          </View>
        </View>
        <DateTimePicker
          isVisible={this.state.isDateTimePickerVisible}
          onConfirm={this._handleDatePicked}
          onCancel={this._hideDateTimePicker}
          mode={"date"}
          maximumDate={new Date()}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
  },
  slider: {
    ...Platform.select({
      ios: {
        height: 0.3 * height,
        backgroundColor: "#C12699",
        borderBottomRightRadius: 65,
      },
      android: {
        height: 0.3 * height,
        backgroundColor: "#009A88",
        borderBottomRightRadius: 65,
      },
    }),
  },
  text: {
    paddingHorizontal: 5,
    justifyContent: "center",
    alignItems: "center",
    fontSize: 30,
    fontWeight: "bold",
    color: "#fff",
  },
  viewText: {
    ...Platform.select({
      ios: {
        height: 150,
        width: Dimensions.get("window").height / 2.6,
        flexDirection: "row",
        backgroundColor: "#C12699",
        justifyContent: "center",
        alignItems: "center",
        borderRadius: 10,
      },
      android: {
        height: 120,
        width: Dimensions.get("window").height / 2,
        flexDirection: "row",
        backgroundColor: "#009A88",
        justifyContent: "center",
        alignItems: "center",
        borderRadius: 10,
        top: 40,
      },
    }),
  },
  dogumGunu: {
    ...Platform.select({
      ios: {
        fontSize: 20,
        color: "#fff",
        fontWeight: "bold",
        borderWidth: 2,
        borderColor: "#fff",
        borderRadius: 10,
        padding: 20,
      },
      android: {
        fontSize: 20,
        color: "#fff",
        fontWeight: "bold",
        borderWidth: 2,
        borderColor: "#fff",
        borderRadius: 10,
        padding: 10,
      },
    }),
  },
  yasHesaplama: {
    ...Platform.select({
      ios: {
        top: 100,
        fontSize: 40,
        color: "#fff",
        fontWeight: "bold",
        borderWidth: 2,
        borderColor: "#fff",
        borderRadius: 10,
        padding: 20,
      },
      android: {
        top: 50,
        fontSize: 35,
        color: "#fff",
        fontWeight: "bold",
        borderWidth: 2,
        borderColor: "#fff",
        borderRadius: 10,
        padding: 10,
      },
    }),
  },
  touchableOpacity: {
    ...Platform.select({
      ios: {
        height: 100,
        width: Dimensions.get("window").height / 3,
        backgroundColor: "#C12699",
        alignItems: "center",
        justifyContent: "center",
        borderRadius: 10,
      },
      android: {
        height: 80,
        width: Dimensions.get("window").height / 2.3,
        backgroundColor: "#009A88",
        alignItems: "center",
        justifyContent: "center",
        borderRadius: 10,
      },
    }),
  },
  anaGovde: {
    ...Platform.select({
      ios: {
        flex: 1,
        justifyContent: "space-between",
        alignItems: "center",
        bottom: 210,
      },
      android: {
        flex: 1,
        justifyContent: "space-between",
        alignItems: "center",
        bottom: 150,
      },
    }),
  },
  solKose: {
    ...Platform.select({
      ios: {
        ...StyleSheet.absoluteFillObject,
        backgroundColor: "#C12699",
      },
      android: {
        ...StyleSheet.absoluteFillObject,
        backgroundColor: "#009A88",
      },
    }),
  },
});


【问题讨论】:

    标签: react-native react-redux react-hooks react-state react-effects


    【解决方案1】:

    我通过 React Hooks 将您的代码重写为函数式编程,并且我在 android 模拟器中对其进行了测试,并且它运行良好。您可以在下面看到一个输出项目的示例:

    以及项目代码:

    import React from "react";
    import {
      StyleSheet,
      Text,
      View,
      Dimensions,
      Platform,
      TouchableOpacity,
    } from "react-native";
    import DateTimePicker from "react-native-modal-datetime-picker";
    
    const { height } = Dimensions.get("window");
    
    const App = ()=> {
    
      const [states , setStates] = React.useState({
        calculated_date: undefined,
        calculated_month: undefined,
        calculated_year: undefined,
        dateOpacity: undefined
      });
    
      const [isDateTimePickerVisible , setIsDateTimePickerVisible] = React.useState(false);
      const [date , setDate] = React.useState(undefined);
    
      const _showDateTimePicker = () => setIsDateTimePickerVisible(true);
      
      const  _hideDateTimePicker = () => setIsDateTimePickerVisible(false);
      
      const _handleDatePicked = (date)=> {
        date = new Date(date);
        return setDate(date);
      };
    
      const _calculateTheDifference = () => {
        if (!date) {
          return;
        }
    
        const currentDate = new Date();
    
        let current_date = currentDate.getDate();
        let current_month = currentDate.getMonth();
        let current_year = currentDate.getFullYear();
    
        let birth_date = date.getDate();
        let birth_month = date.getMonth();
        let birth_year = date.getFullYear();
    
        let month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
        
        if (birth_date > current_date) {
          current_month = current_month - 1;
          current_date = current_date + month[birth_month - 1];
        }
    
        if (birth_month > current_month) {
          current_year = current_year - 1;
          current_month = current_month + 12;
        }
    
        let calculated_date = current_date - birth_date;
        let calculated_month = current_month - birth_month;
        let calculated_year = current_year - birth_year;
    
        if (calculated_date || calculated_month || calculated_year)
          setStates({
            ...states,
            calculated_date,
            calculated_month,
            calculated_year,
            dateOpacity: 1,
          });
      };
    
      React.useEffect(()=>{
          if (date){
            console.log("Selected Date:" , date);
              _hideDateTimePicker();
              _calculateTheDifference();
          };
      } , [date]);
    
      return (
        <View style={styles.container}>
          <View style={styles.slider}>
            <View style={{ justifyContent: "center", alignItems: "center" }}>
              <Text style={styles.yasHesaplama}>Age Calculate</Text>
            </View>
          </View>
          <View style={{ flex: 1, backgroundColor: "#fff" }}>
            <View style={styles.solKose} />
            <View
              style={{
                flex: 1,
                backgroundColor: "#fff",
                borderTopLeftRadius: 65,
              }}
            />
          </View>
          <View style={styles.anaGovde}>
            <TouchableOpacity
              style={styles.touchableOpacity}
              onPress={_showDateTimePicker}
            >
              <Text style={styles.dogumGunu}>Enter your birthday.</Text>
            </TouchableOpacity>
            <View style={[styles.viewText, { padding: 10 }]}>
              <Text style={styles.text}>
                {states.calculated_year}
                {" Year"}{" "}
              </Text>
              <Text style={styles.text}>
                {states.calculated_month}
                {" Month"}{" "}
              </Text>
              <Text style={styles.text}>
                {states.calculated_date}
                {" Date"}{" "}
              </Text>
            </View>
          </View>
          <DateTimePicker
            isVisible={isDateTimePickerVisible}
            onConfirm={_handleDatePicked}
            onCancel={_hideDateTimePicker}
            mode={"date"}
            maximumDate={new Date()}
          />
        </View>
      );
    
    };
    
    export default App;
    
    const styles = StyleSheet.create({
      container: {
        flex: 1,
        backgroundColor: "#fff",
      },
      slider: {
        ...Platform.select({
          ios: {
            height: 0.3 * height,
            backgroundColor: "#C12699",
            borderBottomRightRadius: 65,
          },
          android: {
            height: 0.3 * height,
            backgroundColor: "#009A88",
            borderBottomRightRadius: 65,
          },
        }),
      },
      text: {
        paddingHorizontal: 5,
        justifyContent: "center",
        alignItems: "center",
        fontSize: 30,
        fontWeight: "bold",
        color: "#fff",
      },
      viewText: {
        ...Platform.select({
          ios: {
            height: 150,
            width: Dimensions.get("window").height / 2.6,
            flexDirection: "row",
            backgroundColor: "#C12699",
            justifyContent: "center",
            alignItems: "center",
            borderRadius: 10,
          },
          android: {
            height: 120,
            width: Dimensions.get("window").height / 2,
            flexDirection: "row",
            backgroundColor: "#009A88",
            justifyContent: "center",
            alignItems: "center",
            borderRadius: 10,
            top: 40,
          },
        }),
      },
      dogumGunu: {
        ...Platform.select({
          ios: {
            fontSize: 20,
            color: "#fff",
            fontWeight: "bold",
            borderWidth: 2,
            borderColor: "#fff",
            borderRadius: 10,
            padding: 20,
          },
          android: {
            fontSize: 20,
            color: "#fff",
            fontWeight: "bold",
            borderWidth: 2,
            borderColor: "#fff",
            borderRadius: 10,
            padding: 10,
          },
        }),
      },
      yasHesaplama: {
        ...Platform.select({
          ios: {
            top: 100,
            fontSize: 40,
            color: "#fff",
            fontWeight: "bold",
            borderWidth: 2,
            borderColor: "#fff",
            borderRadius: 10,
            padding: 20,
          },
          android: {
            top: 50,
            fontSize: 35,
            color: "#fff",
            fontWeight: "bold",
            borderWidth: 2,
            borderColor: "#fff",
            borderRadius: 10,
            padding: 10,
          },
        }),
      },
      touchableOpacity: {
        ...Platform.select({
          ios: {
            height: 100,
            width: Dimensions.get("window").height / 3,
            backgroundColor: "#C12699",
            alignItems: "center",
            justifyContent: "center",
            borderRadius: 10,
          },
          android: {
            height: 80,
            width: Dimensions.get("window").height / 2.3,
            backgroundColor: "#009A88",
            alignItems: "center",
            justifyContent: "center",
            borderRadius: 10,
          },
        }),
      },
      anaGovde: {
        ...Platform.select({
          ios: {
            flex: 1,
            justifyContent: "space-between",
            alignItems: "center",
            bottom: 210,
          },
          android: {
            flex: 1,
            justifyContent: "space-between",
            alignItems: "center",
            bottom: 150,
          },
        }),
      },
      solKose: {
        ...Platform.select({
          ios: {
            ...StyleSheet.absoluteFillObject,
            backgroundColor: "#C12699",
          },
          android: {
            ...StyleSheet.absoluteFillObject,
            backgroundColor: "#009A88",
          },
        }),
      },
    });
    
    

    【讨论】:

    • 没有答案?
    • 如果你有一个小项目分享你所有的代码,如果不能把相关代码分享到当前组件,也许我可以帮助你。
    • 我添加了上面的所有代码。主题:1 @MHP
    • @kikirim 前几天我忙于我的项目,无法回复您,希望如果您的问题还没有解决,希望对您有所帮助。祝你好运!
    • 非常感谢。你太棒了:) @MHP
    【解决方案2】:

    它看起来像这样

    import React from 'react';
    import { View, Text } from 'react-native';
    
    import { connect } from 'react-redux';
    
    export default function Rewards(props) {
      const [state, setState] = React.useState({
        isDateTimePickerVisible: false,
        date: undefined,
        millSecLeft: 0,
        dateOpacity: 1,
      });
    
      console.log(props); // Your props here
    
      const _showDateTimePicker = () =>
        setState({ ...state, isDateTimePickerVisible: true });
    
      const _hideDateTimePicker = () =>
        setState({ ...state, isDateTimePickerVisible: false });
    
      const _handleDatePicked = (date) => {
        date = new Date(date);
        setState({ date: date }, () => {
          _hideDateTimePicker();
          _calculateTheDifference();
        });
      };
    
      const _calculateTheDifference = () => {
        if (!state.date) {
          return;
        }
        let current_date = new Date().getDate();
        let current_month = new Date().getMonth();
        let current_year = new Date().getFullYear();
        let birth_date = state.date.getDate();
        let birth_month = state.date.getMonth();
        let birth_year = state.date.getFullYear();
        let month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
        if (birth_date > current_date) {
          current_month = current_month - 1;
          current_date = current_date + month[birth_month - 1];
        }
        if (birth_month > current_month) {
          current_year = current_year - 1;
          current_month = current_month + 12;
        }
        let calculated_date = current_date - birth_date;
        let calculated_month = current_month - birth_month;
        let calculated_year = current_year - birth_year;
        if (calculated_date || calculated_month || calculated_year)
          setState({
            ...state,
            calculated_date: calculated_date,
            calculated_month: calculated_month,
            calculated_year: calculated_year,
            dateOpacity: 1,
          });
      };
    
      return <View>{/*Code here*/}</View>;
    }
    

    【讨论】:

    • 感谢您的帮助,我添加了所有代码,您的代码失败了。
    • ERROR 警告:来自 useState() 和 useReducer() Hooks 的状态更新不支持第二个回调参数。要在渲染后执行副作用,请在组件主体中使用 useEffect() 声明它。
    【解决方案3】:

    您无法在反应钩子中将回调函数作为 setState 中的第二个参数传递(它仅适用于 Class 组件),因此您可以改用 useEffect 和控制您的应用程序生命周期。对于这种情况,您可以按照以下方式操作:

    React.useEffect(()=> {
       if ( state.date ){
         _hideDateTimePicker();
         _calculateTheDifference();
       };
    } , [state])
    

    您还需要将 _handleDatePicked 更改为:

    const _handleDatePicked = (date) => {
        date = new Date(date);
        setState({ 
           ...state,
           date: date 
        });
    };
    

    【讨论】:

      【解决方案4】:

      修复已完成,但不起作用。

      
      function Rewards({ appTheme }) {
        const [state, setState] = useState({
          isDateTimePickerVisible: false,
          date: undefined,
        });
      
        const _showDateTimePicker = () =>
          setState({ ...state, isDateTimePickerVisible: true });
      
        const _hideDateTimePicker = () =>
          setState({ ...state, isDateTimePickerVisible: false });
      
        useEffect(() => {
          if (state.date) {
            _hideDateTimePicker();
            _calculateTheDifference();
          }
        }, [state]);
      
        const _handleDatePicked = (date) => {
          date = new Date(date);
          setState({
            ...state,
            date: date,
          });
        };
        const _calculateTheDifference = () => {
          if (!state.date) {
            return;
          }
          let current_date = new Date().getDate();
          let current_month = new Date().getMonth();
          let current_year = new Date().getFullYear();
          let birth_date = state.date.getDate();
          let birth_month = state.date.getMonth();
          let birth_year = state.date.getFullYear();
          let month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
          if (birth_date > current_date) {
            current_month = current_month - 1;
            current_date = current_date + month[birth_month - 1];
          }
          if (birth_month > current_month) {
            current_year = current_year - 1;
            current_month = current_month + 12;
          }
          let calculated_date = current_date - birth_date;
          let calculated_month = current_month - birth_month;
          let calculated_year = current_year - birth_year;
          if (calculated_date || calculated_month || calculated_year)
            setState({
              ...state,
              calculated_date: calculated_date,
              calculated_month: calculated_month,
              calculated_year: calculated_year,
              dateOpacity: 1,
            });
        };
      
        return (
          <View style={styles.container}>
            <HeaderBarYas />
      
            <FlatList
              style={{
                marginTop: -25,
                borderTopLeftRadius: SIZES.radius * 2,
                borderTopRightRadius: SIZES.radius * 2,
                backgroundColor: COLORS.lightGray3,
              }}
            />
            <View style={styles.anaGovde}>
              <TouchableOpacity
                style={styles.touchableOpacity}
                onPress={_showDateTimePicker}
              >
                <Text style={styles.dogumGunu}>Doğum Gününü Giriniz</Text>
              </TouchableOpacity>
              <View style={[styles.viewText, { padding: 10 }]}>
                <Text style={styles.text}>
                  {state.calculated_year}
                  {" Yıl"}{" "}
                </Text>
                <Text style={styles.text}>
                  {state.calculated_month}
                  {" Ay"}{" "}
                </Text>
                <Text style={styles.text}>
                  {state.calculated_date}
                  {" Gün"}{" "}
                </Text>
              </View>
            </View>
            <DateTimePicker
              isVisible={state.isDateTimePickerVisible}
              onConfirm={_handleDatePicked}
              onCancel={_hideDateTimePicker}
              mode={"date"}
              locale="tr_TR"
              maximumDate={new Date()}
            />
          </View>
        );
      }
      
      

      【讨论】:

      • 实际上您共享的屏幕截图显示,作为第二个参数的回调函数导致错误,那么您在应用更改后是否在当前组件中收到相同的错误或错误是另一个组件?跨度>
      • 警告:已超过最大更新深度。当组件在 useEffect 中调用 setState 时,可能会发生这种情况,但 useEffect 要么没有依赖数组,要么每次渲染时依赖项之一发生变化。
      • 这意味着你有无限时间更新状态!换句话说,放在无限循环中,我建议您将“日期”与其他状态分开并为此单独创建状态并将其设置在 useEffect 依赖项中。
      • 怎么做,不知道你能不能帮忙。
      • 现在我看到你的代码更准确了,你在 useEffect 中犯了一个错误,你使用 _handleDatePicked 而不是 _hideDateTimePicker 并且它会导致无限循环。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-26
      • 2020-06-25
      • 1970-01-01
      • 2018-03-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多