简体   繁体   中英

how do a set a boolean value to false from one react component to main app.js

trying to use the handle submit function to change the isAuthinticated to true from false thats on the main app.js file thats using react router.. all of the redux examples i look at are all using an app js file that has the onclick function on it not react router. thank you if you can help

function App () {
    return (
      <Router>
      <div>
        <Switch>
          <Route exact path="/" component={Login} />
          <Route exact path="/login" component={Login} />
          <Route exact path="/signup" component={Signup} />
          <PrivateRoute 
          exact path="/mainpage" 
          component={MainPage} 
          isAuthenticated={false}
          />
        </Switch>
      <Footer />
      </div>
    </Router>
    );
  }
export default App;

my login.js that has the click event

const Login = () => {
  const history = useHistory()
  const [state, setState] = useState({
    email: '',
    password: ''
   });
  
  const [validate, setValid] = useState({
   validateEmail: '',
   validatePassword: '', 
  }) 
  
  
const handleInputChange = event => setState({
    ...state,
    [event.target.name]: event.target.value,
  })

  const handleSubmit = user => {
    if(state.password === ''){
     setValid({validatePassword:true})
    }
    if(state.email === '' ){
     setValid({validateEmail:true})
    }

    axios.post(`auth/login`, state )
    .then(res => {
      console.log(res);
      console.log(res.data);  
      if (res.status === 200 ) {
        history.push('/mainpage');
      }  
    })
    .catch(function (error) {
      console.log(error);
      alert('Wrong username or password')
      window.location.reload();
    });
  }


  // console.log('state', state)
  const {email, password } = state

  const [popoverOpen, setPopoverOpen] = useState(false);

  const toggle = () => setPopoverOpen(!popoverOpen);
 
    return (
    <>
      <Container>
        <Row>
          <Col>
          <img src={logo} alt="Logo" id="logo" /> 
            <Button id="Popover1" type="button">
               About Crypto-Tracker
            </Button>
          <Popover placement="bottom" isOpen={popoverOpen} target="Popover1" toggle={toggle}>
            <PopoverHeader>About</PopoverHeader>
            <PopoverBody>Your personalized finance app to track all potential cryptocurrency investments</PopoverBody>
          </Popover>
          </Col>
          <Col sm="2" id="home" style={{height: 500}}>
            <Card body className="login-card">
              <Form className="login-form">
                <h2 className="text-center">Welcome</h2>
                <h3 className="text-center">____________</h3>
                <FormGroup>
                  <Label for="exampleEmail">Email</Label>
                  <Input invalid={validate.validateEmail}  onChange = {handleInputChange} value = {email} type="email"  required name="email" placeholder="email" />
                  <FormFeedback>Please enter email</FormFeedback>
                </FormGroup>
                <FormGroup>
                  <Label for="examplePassword">Password</Label>
                  <Input invalid={validate.validatePassword}   onChange = {handleInputChange} value = {password} type="password" required name="password" placeholder="password"/>
                  <FormFeedback>Please enter password</FormFeedback>
                </FormGroup>
                <Button  onClick={()=> handleSubmit(state)} className="but-lg btn-dark btn-block">Login</Button>
                <div className="text-center pt-3"> or sign in with Google account</div>
                <Loginbutton />
                <div className="text-center">
                  <a href="/signup"> Sign up</a>
                  <span className="p-2">|</span>
                  <a href="/ForgotPw">Forgot password</a>
                </div>
              </Form>
            </Card>
          </Col>
        </Row>
      </Container>
    </>
    );
  }

export default Login;

代码

authslice.js using asyncthunk

import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'
import { userAPI } from '../../../server/routes/authRoutes'

const fetchAuth = createAsyncThunk(
    'auth/login',
    async (userId, thunkAPI) => {
      const response = await userAPI.fetchById(userId)
      return response.data
    }
  )

  const authSlice = createSlice({
    name: 'isAuthenticated',
    initialState: {
      value: false,
    },
    reducers: {
    //   Authenticated: state => {
        // Redux Toolkit allows us to write "mutating" logic in reducers. It
        // doesn't actually mutate the state because it uses the Immer library,
        // which detects changes to a "draft state" and produces a brand new
        // immutable state based off those changes
        // state.value = true;
    //   },
    },
    extraReducers: {
        [fetchAuth.fulfilled]: state  => {
            // Add user to the state array
                state.value = true
          },
        [fetchAuth.rejected]: state => {
            // Add user to the state array
            state.value = false
        }
    }
  });

  dispatch(fetchUserById(123))
  
//   export const { increment, decrement, incrementByAmount } = counterSlice.actions;

This would be easy to achieve if you use some kind of global store to store such values. Typical options include Redux, Mobx, etc.

Define your isAuthenticated variable as a global store variable. mutate its value using corresponding package methods like Redux dispatch events or similar from your functions anywhere else in the app.

You can try it using Redux, creating a store to the login variables, and sharing it with the component App.js.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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