简体   繁体   English

我在React中有一个重定向问题

[英]I have a problem with redirection in React

I am new to react and i am creating a simple Contact Manager App, i have contacts and addContact components, these are separated in different routes. 我是新来的反应者,我正在创建一个简单的Contact Manager App,我有联系人和addContact组件,这些组件以不同的方式分开。 When i add a contact,it gets added to the local storage and the contacts component is getting the list of contacts from the local storage. 当我添加联系人时,它会添加到本地存储中,而联系人组件正在从本地存储中获取联系人列表。 The problem that when i add a contact and i redirect to the contacts page, the new contact doesn't show unless i manually refresh the page. 当我添加联系人并重定向到联系人页面时,除非我手动刷新页面,否则不会显示新联系人的问题。

i tried this : 我尝试了这个:

this.props.history.push('/');

this too 这个也是

window.location.href=window.location.hostname;

and i created a function to refresh the page if the previous link is the addContact link, it doesn't work either 我创建了一个函数来刷新页面,如果上一个链接是addContact链接,那么它也不起作用

this is the App component code: 这是应用程序组件代码:

 import React from 'react'; import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'; import Navbar from './components/navbar'; import Contacts from './components/contacts'; import About from './components/pages/about'; import AddContact from './components/pages/addContact' import NotFound from './components/pages/notFound' function getContactsLS() { let contacts; if (localStorage.getItem('contacts') === null) { contacts = []; } else { contacts = JSON.parse(localStorage.getItem('contacts')); } contacts = Array.from(contacts); return contacts; } class App extends React.Component { contactsLS = getContactsLS(); render() { return ( <Router> <Navbar /> <div className="container"> <Switch> <Route exact path="/add-contact" component={AddContact} /> <Route exact path="/" component={() => <Contacts contacts={this.contactsLS} />} /> <Route exact path="/about" component={About} /> <Route component={NotFound}/> </Switch> </div> </Router> ) } } export default App 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> 

this is addContact function : 这是addContact函数:

 addContactEvent = () =>{ let contacts; if(localStorage.getItem('contacts')===null) contacts=[]; else{ contacts=JSON.parse(localStorage.getItem('contacts')); } contacts=Array.from(contacts); console.log(contacts); this.setState({key:contacts.length}); const contact = { key : contacts.length, name: this.state.name, email:this.state.email, phone:this.state.phone } contacts.push(contact); localStorage.setItem('contacts', JSON.stringify(contacts)); //redirection //this.props.history.push('/'); window.location.href=window.location.hostname; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.1/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.1/umd/react-dom.production.min.js"></script> 

You could use <Redirect> component from react-router-dom package. 您可以使用react-router-dom包中的<Redirect>组件。 To get it working you initially setState where redirect is set to false. 为了使其正常工作,您首先将setState设置为redirect,将redirect设置为false。

this.state = {
  redirect: false
}

Once the addContact opeartion is done, update the state 完成addContact操作后,请更新状态

this.setState({
  redirect: true
})

Inside of your AddContact component, the state will decide if it has to show the actual component or to redirect to the attached path. 在您的AddContact组件内部,状态将决定是否必须显示实际组件或重定向到附加路径。 Something like this: 像这样:

import {Redirect } from 'react-router-dom';
class AddContact extends React.Component {
  //Add the initial state
  // addContact Operation
  render(){
    if(this.state.redirect)
      return <Redirect to="/" />
    return (
       //The markup for AddContact
    )

  }
}

It feels like you would want the contacts as part of the state. 感觉就像您希望将联系人作为州的一部分。 In that case the code would be: 在这种情况下,代码将是:

state = { contactLS: getContactsLS()}

But as we are calling values from localStorage a more appropriate place might be componentDidMount() method.From react docs 但是,正如我们从localStorage的调用值更合适的地方可能是componentDidMount() method.From反应文档

Avoid introducing any side-effects or subscriptions in the constructor. 避免在构造函数中引入任何副作用或订阅。 For those use cases, use componentDidMount() instead. 对于这些用例,请改用componentDidMount()。

Then the code would be 然后代码将是

componentDidMount(){
    const contacts =  getContactsLS()
    this.setState({ contacsLS: contacts })
}

Don't forget to change to this.state.contactsLS 不要忘记更改为this.state.contactsLS

<Route exact path="/" component={() => <Contacts contacts={this.state.contactsLS} />} />

==== ====

PS 聚苯乙烯
Another problem i can see in the existing code is the misuse of component constructor. 我可以在现有代码中看到的另一个问题是滥用组件构造函数。
This is not obvious but the line 这不是很明显,但是线

contactsLS = getContactsLS();

is equivalent to 相当于

constrcutor(){
   this.contactLS = getContactLS();
}

from react documentation we read 从我们阅读的反应文档中

Typically, in React constructors are only used for two purposes: 通常,在React中,构造函数仅用于两个目的:
- Initializing local state by assigning an object to this.state. -通过将对象分配给this.state来初始化本地状态。
- Binding event handler methods to an instance. -将事件处理程序方法绑定到实例。

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

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