繁体   English   中英

如何将 boolean 值从一个反应组件设置为 false 到主 app.js

[英]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它没有反应路由器。 谢谢你,如果你能帮忙

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;

我的 login.js 有点击事件

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 使用 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;

如果您使用某种全局存储来存储这些值,这将很容易实现。 典型选项包括 Redux、Mobx 等。

将您的isAuthenticated变量定义为全局存储变量。 使用相应的 package 方法(如 Redux 调度事件或类似应用程序中其他任何位置的函数)改变其值。

您可以使用 Redux 进行尝试,为登录变量创建一个存储,并与组件 App.js 共享它。

暂无
暂无

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

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