Реагируйте: кнопка не работает / не может выполнить обновление состояния - PullRequest
0 голосов
/ 26 июня 2019

Я написал следующий веб-сайт: https://konekto -hgol6b5mz.now.sh

Если вы быстро щелкнете по настройке и настройкам, вы увидите, что у меня один экран сКнопка «Прямой SOS».Однако его функция не выполняется, и поэтому я не перенаправлен.Здесь вы можете увидеть класс, относящийся к этому:

import React from 'react';
import { Button, Grid } from '@material-ui/core';
import { withStyles } from '@material-ui/core/styles';
import AppContext from '../utils/AppContext';

const styles = theme => ({
  container: {
    alignItems: 'center',
    // background: 'white',
    border: 'black',
    'border-width': 'medium',
    'margin-top': '80px',
    background: 'rgba(255, 255, 255, 0.8)',
    'border-radius': '20px'
  },
  item: {
    // background: 'red',
    width: '100%',
    //background: 'white',
    'text-align': 'center',
    'border-radius': '5px',
    'margin-top': '10px'
  },
  sosbutton: {
    background: 'red',
    'text-align': 'center',
    'margin-top': '30px',
    height: '80%',
    width: '100%'
  }
});

class Landingpage extends React.Component {
  static contextType = AppContext;

  constructor(props) {
    super(props);
    this.classes = props.classes;
    this.state = {};
    this.handleDirectSOS = this.handleDirectSOS.bind(this);
  }

  componentDidMount() {
    console.log(this.context);

    if (this.context.onBoardingStatus === false) {
      console.log('IN IF');
      this.props.history.push('/onboarding');
    }
  }
  handleDirectSOS() {
    console.log('direct SOS');
    this.props.history.push('/emergency_sent');
  }
  render() {
    console.log('direct SOS');
    return (
      <Header title="Send out SOS" />
      <Grid
        container
        className={this.classes.container}
        direction="column"
        spacing={2}
      >
        <Grid
          item
          sm={12}
          className={(this.classes.item, this.classes.forwardbutton)}
        >
          <Button
            className={this.classes.sosbutton}
            name="type_person"
            value="1"
            onClick={this.props.handleDirectSOS}
          >
            Direct SOS
          </Button>
        </Grid>
      </Grid>
    );
  }
}

export default withStyles(styles)(Landingpage);

index.js: 1375 Предупреждение: Невозможно выполнить обновление состояния React на отключенном компоненте.Это не работает, но это указывает на утечку памяти в вашем приложении.Чтобы исправить, отмените все подписки и асинхронные задачи в методе componentWillUnmount.в настройках (созданных WithStyles (Настройки)) в WithStyles (Настройки) (созданных Context.Consumer)

Это может быть связано с файлом настроек, но я понятия не имею, в чем может быть причина.Здесь вы можете увидеть файл настроек:

import React from 'react';
import axios from 'axios';
import {
  Grid,
  Box,
  Container,
  Typography,
  Button,
  TextField
} from '@material-ui/core';

import { withStyles } from '@material-ui/core/styles';
import Header from '../Layout/Header';

import CONST from '../utils/Constants';

const CssTextField = withStyles({
  root: {
    '& label.Mui-focused': {
      color: 'green'
    },
    '& .MuiInput-underline:after': {
      borderBottomColor: 'green'
    },
    '& .MuiOutlinedInput-root': {
      '& fieldset': {
        borderColor: 'red'
      },
      '&:hover fieldset': {
        borderColor: 'yellow'
      },
      '&.Mui-focused fieldset': {
        borderColor: 'green'
      }
    }
  },
  layout: {
    width: '100%'
  }
})(TextField);

const styles = theme => ({
  root: {
    display: 'flex',
    flexWrap: 'wrap',
    width: '100%'
  },
  title: {
    'text-align': 'center'
  },
  textfield: {
    'margin-top': theme.spacing(1),
    'margin-bottom': theme.spacing(2)
  }
});

//const classes = useStyles();

class Settings extends React.Component {
  constructor(props) {
    super(props);
    //const { classes } = props;
    this.classes = props.classes;
    this.state = {};
    this.onChangeText = this.onChangeText.bind(this);
    this.onSubmit = this.onSubmit.bind(this);
  }

  onChangeText(e) {
    console.log('text has changed.');
    const key = e.target.id;
    const value = e.target.value;
    let state_obj = {};
    state_obj[key] = value;
    this.setState(state_obj);
  }

  onSubmit(e) {
    console.log('Submit button pressed.');
    axios
      .post(CONST.URL + 'user/update', {
        id: 1,
        data: this.state
      })
      .then(res => {
        console.log(res);
        console.log(res.data);
      })
      .catch(err => {
        console.log(err);
      });
    this.props.history.push('/');
  }

  componentDidMount() {
    console.log('Component did mount.');
    axios
      .get(CONST.URL + 'user', {
        params: { id: 1 }
      })
      .then(resp => {
        // console.log(resp);
        const data = resp.data.data;
        this.setState(data);
        console.log(this.state.fullname);
      })
      .catch(function(error) {
        console.log(error);
      })
      .then(function() {
        // always executed
      });
  }

  render() {
    return (
      <React.Fragment>
        <Header title="Settings" BackButton="true" />
        <Container component="main" maxWidth="sm">
          {/* <Typography variant="h4" align="center" gutterBottom="true">
            Settings
          </Typography> */}
          <Box className={this.classes.textfield}>
            <Grid
              container
              direction="column"
              justify="flex-end"
              alignItems="left"
              item
              xs
            >
              <Typography variant="h6">Personal Information</Typography>
              <CssTextField
                id="fullname"
                label="Fullname"
                onChange={this.onChangeText}
                value={this.state.fullname}
              />
              <CssTextField
                id="birthday"
                label="Birthday"
                onChange={this.onChangeText}
                value={this.state.birthday}
              />
              <CssTextField
                id="address"
                label="Home address"
                onChange={this.onChangeText}
                value={this.state.address}
              />
            </Grid>
          </Box>
          <Box className={this.classes.textfield}>
            <Grid
              container
              direction="column"
              justify="flex-end"
              alignItems="left"
              item
              xs
            >
              <Typography variant="h6">Health information</Typography>
              <CssTextField
                id="allergies"
                label="Allergies"
                onChange={this.onChangeText}
                value={this.state.allergies}
              />
              <CssTextField
                id="past_injuries"
                label="Past injuries"
                onChange={this.onChangeText}
                value={this.state.past_injuries}
              />
            </Grid>
          </Box>
          <Box className={this.classes.textfield}>
            <Grid
              container
              direction="column"
              justify="flex-end"
              alignItems="left"
              item
              xs
            >
              <Typography variant="h6">Contact information</Typography>
              <CssTextField
                id="fullname_relative_1"
                label="Fullname relative 1"
                onChange={this.onChangeText}
                value={this.state.fullname_relative_1}
              />
              <CssTextField
                id="phone_number_relative_1"
                label="Phone number relative 1"
                onChange={this.onChangeText}
                value={this.state.phone_number_relative_1}
              />
              <CssTextField
                id="fullname_relative_2"
                label="Fullname relative 2"
                onChange={this.onChangeText}
                value={this.state.fullname_relative_2}
              />
              <CssTextField
                id="phone_number_relative_2"
                label="Phone number relative 2"
                onChange={this.onChangeText}
                value={this.state.phone_number_relative_2}
              />
            </Grid>
          </Box>
          <Box>
            <Grid
              container
              direction="column"
              justify="flex-end"
              alignItems="left"
              item
              xs
            >
              <Button
                variant="contained"
                className={this.classes.button}
                onClick={this.onSubmit}
              >
                Save
              </Button>
              <br />
              {/* <Button
                variant="contained"
                className={this.classes.button}
                onClick={() => {
                  this.props.history.push('/');
                }}
              >
                Cancel emergency
              </Button> */}
              {/* <br /> */}
              <Button
                variant="contained"
                className={this.classes.button}
                onClick={() => {
                  this.props.history.push('/onboarding_reset');
                }}
              >
                Reset App
              </Button>
              {/* <br />
              <Button
                variant="contained"
                className={this.classes.button}
                onClick={() => {
                  this.props.history.push('/Signin');
                }}
              >
                Signin
              </Button> */}
            </Grid>
          </Box>
        </Container>
      </React.Fragment>
    );
  }
}

export default withStyles(styles)(Settings);

Буду очень признателен за вашу помощь!

1 Ответ

0 голосов
/ 26 июня 2019

Я думаю, у вас есть две отдельные проблемы.

Проблема с нажатием кнопки вызвана тем, что вы звоните onClick={this.props.handleDirectSOS} вместо onClick={this.handleDirectSOS}

Ошибка, которую вы видите из-за строки this.setState(data);, вам нужно обернуть это или отменить вызов, если компонент отключен. На нем довольно много статей, таких как Есть ли способ проверить, отключен ли компонент реагирования?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...