【发布时间】:2020-09-01 19:19:07
【问题描述】:
我开始使用 react-router,我发现我可以在 Link 组件中传递“props”,这样一些值就可以传递给另一个组件。我在我正在使用的按钮内发送一个名为“值”的组件,但是在接收该参数的组件中显示一条错误消息,消息为“对象可能为空或未定义”。
这是我的代码:
我将数据发送到哪里:
<Container placeholder>
<Segment>
<Form>
<Form.Field>
<label>Correo</label>
<input placeholder='Ingresa tu correo' name='nombre' onChange={actualizarUser}/>
</Form.Field>
<Form.Field>
<label>Contraseña</label>
<input placeholder='Ingresa tu contraseña' name='password' onChange={actualizarUser}/>
</Form.Field>
<Link to={{ pathname:'/init/home', state:{ value: token } }}> // Here I'm sending the props to the next component
<Button type='submit'>SubmitNuevo</Button>
</Link>
<Button type='submit' onClick={sendInfo}>Prueba</Button>
</Form>
</Segment>
</Container>
以及我收到 location.state 的组件
const Logged: React.FC<{}> = () => {
const [open, setOpen] = useState(false);
const location = useLocation(); // Here I'm using useLocation to capture the props I sent
const [token, setToken] = useState('');
useEffect(() => {
console.log(location.state);
setToken(location.state.value); // Here is were I'm getting the error message
console.log(token);
});
const handleOpen = () => {
setOpen(true);
}
const handleClose = () => {
setOpen(false);
}
return(<div>
</div>
);
我也尝试将其作为道具进行管理,但是还有另一个错误显示它好像无法识别位置:
这是关于我在哪里使用 Route 和 props 传递信息的第二个选项的信息
function App() {
return (
<div className="App">
<Navbar bg="dark" variant="dark">
<Navbar.Brand href="#home">
Micrin
</Navbar.Brand>
</Navbar>
<Router>
<Switch>
<Route path='/login' component={InicioSesion} />
<Route path='/register' component={Registro} />
<Route path='/recover' component={RecuperarCuenta}/>
<Route path='/init/home' exact component={Logged} />
<Route path='/init/stock' exact component={Logged} />
<Route path='/init/menu' exact component={Logged} />
<Route path='/init/sales' exact component={Logged} />
<Route path='/init/market' exact component={Logged} />
<Route path='/' component={MainPage} />
</Switch>
</Router>
</div>
);
}
以及我发送的带有道具的组件渲染
const Logged: React.FC<{}> = (props) => {
const [open, setOpen] = useState(false);
const [token, setToken] = useState('');
useEffect(() => {
console.log(props.location.state);
setToken(props.location.state.value); // Shows error message 'Property location does not exist on type {children?: ReactNode}'
console.log(token);
});
const handleOpen = () => {
setOpen(true);
}
const handleClose = () => {
setOpen(false);
}
return(
<div></div>
);
感谢您的帮助
【问题讨论】:
标签: javascript reactjs typescript react-router