【问题标题】:how to activityindicator react native如何让activityindicator反应原生
【发布时间】:2020-05-09 23:51:39
【问题描述】:

我有一个登录设置,可与我的 api 一起使用获取并在完成时再次将其设置为 false,但我无法在与获取 api 的文件相同的 js 中声明活动指示器

这是我的登录表单组件,名为 AuthForm

 export default function AuthForm  ({ errorMessage, onSubmit }) {

  const [vCellphone, setvCellphone] = useState('');
  const [vPassword, setvPassword] = useState('');
  const [secureTextEntry, setSecureTextEntry] = useState(true);

  onPassPress = () => {
    setSecureTextEntry(!secureTextEntry);
  }

  handleChange = e => {
    const { value, name } = e.target;
    this.setState({ [name]: value });
  };

  return (
    <View style={styles.container}>
      <Image style={styles.logo} source={require('../assets/Logotipo-All.png')} />
      <Text style={styles.textIniciar}>Iniciar sesión</Text>
      <Text style={styles.textIniciar}></Text>
      <View style={styles.inputContainer}>
        <TextInput style={styles.inputs}
          placeholder="Teléfono"
          underlineColorAndroid='transparent'
          onChangeText={newvCellphone => setvCellphone(newvCellphone)}
          keyboardType={'numeric'}
          value={vCellphone}
          autoCorrect={false}
          autoCompleteType = "off"
          required
        />
      </View>
      <View style={styles.inputContainer}>
        <TextInput style={styles.inputs}
          placeholder="Contraseña"
          secureTextEntry={secureTextEntry} 
          underlineColorAndroid='transparent'
          onChangeText={newvPassword => setvPassword(newvPassword)}
          value={vPassword}
          autoCorrect={false}
        />
        <TouchableOpacity  onPress={this.onPassPress}>
          <Image style={styles.inputIcon} source={require('../assets/Visualización.png')}/>
        </TouchableOpacity>
      </View>

      <TouchableOpacity style={[styles.buttonContainer, styles.loginButton]}  
        onPress={() => onSubmit({ vCellphone, vPassword })}>
        <Text style={styles.loginText}>INGRESAR</Text>
      </TouchableOpacity>
    </View>

  );
};

这是我的 api 调用代码,称为 AuthContext

  const login  = dispatch => async ({ vCellphone, vPassword }) => {
    const response = await ForceApi.post('/LoginController.php', { vCellphone, vPassword });
    const Validar = response.data.error;
    await AsyncStorage.setItem('id', response.data.id);
    dispatch({ type: 'login', payload: response.data.id});
    if(Validar == false ){
    navigate('Panel');
    } 
};
export const {Provider, Context} = createDataContext(
    authReducer,
    { login, logout, clearErrorMessage, tryLocalSignin, guardar,},
    {id:null, vSolicitudeId:null,errorMessage: ''}, []
);

这是调用 AuthForm 的视图

    import { Context } from '../context/AuthContext';
import AuthForm from '../components/AuthForm';
import { NavigationEvents } from 'react-navigation';


const IniciarSesion = () => {
  const { state, login, clearErrorMessage} = useContext(Context);
  onPassPress = () => {
    this.setState({
      secureTextEntry: !this.state.secureTextEntry
    });
  }
  return (

    <View style={styles.container}>
      <NavigationEvents
        onWillBlur = {clearErrorMessage}
      />
      <AuthForm 
        errorMessage = {state.errorMessage}
        onSubmit = {login}
      /> 
    </View>
  );
};

任何帮助将不胜感激

【问题讨论】:

  • 问题解决了???

标签: reactjs react-native


【解决方案1】:

TL;DR您需要有条件地呈现 ActivityIndi​​cator。

您可能想在组件中创建一个“正在加载”状态变量,例如

const [loading, setLoading] = useState(true);

然后在您的渲染方法中,有条件地渲染 ActivityIndi​​cator

  return loading ? (
<View style={{flex: 1, justifyContent: 'center'}}>
  <ActivityIndicator size="large" />
</View>
) : (<YourComponent />);

YourComponent 是不加载时显示的组件。

目前loading 状态默认初始化为 true,因此 ActivityIndi​​cator 将始终显示正在加载。在您的 useEffect 挂钩中,您应该在调用 API 或加载数据后将 setLoading 设置为 false。或者,您可以将默认初始化设置为 false,以便显示 YourComponent。

更多信息请访问react native website

【讨论】:

  • 但是我怎么知道它什么时候停止加载?我不能把钩子放在 context.js 中
  • 当您希望它停止加载时,必须使用setLoading(false) 使其停止加载。例如,如果您正在从获取请求中加载信息,请在回调中调用 setLoading(false)。这将仅在返回响应后删除 ActivityIndi​​cator。
【解决方案2】:

在您的组件中创建“isLoading”状态并在表单提交之前将其设置为 true,稍后您可以在收到响应后将 isLoading 设置为 false。

onSubmit上,可以传递成功回调,例如

onPress={() => {
  this.setState({
    isLoading: true,
  });

  onSubmit({
    vCellphone,
    vPassword,
    successCB: () => {
      this.setState({
        isLoading: false,
      });
    },
  });
}}

然后在登录逻辑调用成功回调成功,例如

const login = dispatch => async ({ vCellphone, vPassword, successCB }) => {
  // your code
  if(successLogin) {
    successCB()
  }
  // navigate
};

注意:您还可以使用 redux 来维护您的 isLoading 状态。

【讨论】:

    【解决方案3】:
    export default function name(){
        const [isLoading, setIsLoading] = useState(true);
    
        useEffect(() => {
            setTimeout(() => {
                setIsLoading(false);
            }, 5000);
        }, []);
    
        if(isLoading){
            return(
                <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
                    <ActivityIndicator size="large"/>
                </View>
            );
        }
    
        return(
        ...your code...
        )
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-05-07
      • 1970-01-01
      • 2022-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多