调用另一个页面后如何在 React 中保留状态值

How to preserve a state value in React after call to another page

我有一个简单的 React/Spring 启动应用程序,我想将搜索字符串传递到详细信息页面,然后 link 使用相同的 searchString 作为参数返回父级。

此时,父页面应获取该值并将其存储回状态。

就现有的代码而言,当parent打开时,它在状态中设置了一堆值,包括搜索字符串:

constructor(props) {
    super(props);
    const {cookies} = props;
    this.state = {
      word: '',
      newWord: '',
      searchString: '',
      licenses: [],
      licensePage: [],
      csrfToken: cookies.get('XSRF-TOKEN'), 
      isLoading: true,
      licensesPerPage: 7,
      activePage: 1,
      begin: 0,
      end: 7
    };

详情页(编辑页)在父页按一个按钮调用:

<Button size="sm" color="primary" tag={Link} to={"/licenses/" + license.id}>Edit</Button>

通过选择“保存”或“取消”按钮将详细信息页面 returns 发送给家长:

<div>
    <Button color="primary" type="submit">Save</Button>{' '}
    <Button color="secondary" tag={Link} to="/licenses">Cancel</Button>
</div>

提交由调用“handleSubmit:

的“onSubmit”函数处理
<Form onSubmit={this.handleSubmit}>

这是 handleSubmit - 只有最后一行与此处相关:

async handleSubmit(event) {

    event.preventDefault();

    if(this.handleValidation()){
    } else {
      return;
    }

    const {item, csrfToken} = this.state;

    await fetch('/api/license' + (item.id ? '/' + item.id : '') , {
      method: (item.id) ? 'PUT' : 'POST',
      headers: {
        'X-XSRF-TOKEN': csrfToken,
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(item),
      credentials: 'include'
    });
    this.props.history.push('/licenses');
  }

这是我需要更改的最后一行:

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

应该是:

this.props.history.push('/license/search/{searchString}');

我只需要填充 searchString。然后我可以将相同的逻辑应用于取消。

所以我的问题是,如何将 searchString 传递给子项,然后在 URL?

传递给父项时抓取它

======================= 尝试实施因“无效”错误而失败的答案==========

我尝试了答案,但无法将其转换为基于 class 的方法(我使用的是 classes,而不是函数)。

这是代码。请注意,我临时将“2”添加到变量名称中,以免与现有代码混淆。

App.js

import React, { Component } from 'react';
import './App.css';
import Home from './Home';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import LicenseList from './LicenseList';
import LicenseEdit from './LicenseEdit';
import ImportList from './ImportList';
import { CookiesProvider } from 'react-cookie';

class App extends Component {

 state = {
    searchString2: ""
  };

  updateSearchString2 = (searchString2) => {
    this.setState({
      searchString2
    });
  };

  render() {
    return (
      <CookiesProvider>
        <Router>
          <Switch>
            <Route path='/' exact={true} component={Home}/>
            <Route path='/licenses' exact={true} component={LicenseList}
                searchString2={this.state.searchString2} // props passed will be same value passed to DetailsPage
                updateSearchString2={this.updateSearchString2}
            />
            <Route path='/imports' exact={true} component={ImportList}/>
            <Route path='/licenses/:id' component={LicenseEdit}/>
          </Switch>
        </Router>
      </CookiesProvider>
    )
  }
}

export default App;

许可证中的相关代码list.js

  <div>
    <input type="text" value={this.props.searchString2} onChange={(e) =>  this.props.updateSearchString2(e.target.value)} />

这给出了错误

TypeError: _this6.props.updateSearchString2 is not a function

有什么想法吗?

您可以为 searchString 状态提供 1 个真实来源,这样,该状态将作为 prop 传递给“ParentPage”组件和“DetailsPage”组件。为此,您可以为 ParentPage 和 DetailsPage 组件使用一个公共父组件

export default class App extends React.Component {
  state = {
    searchString: ""
  };

  updateSearchString = (searchString) => {
    this.setState({
      searchString
    });
  };

  render() {
    return (
      <div className="App">
        <Route
          exact
          path="/"
          render={() => (
            <ParentPage
              searchString={this.state.searchString} // props passed will be same value passed to DetailsPage
              updateSearchString={this.updateSearchString}
            />
          )}
        />
        <Route
          path="/license"
          render={() => <DetailsPage searchString={this.state.searchString} />}
        />
      </div>
    );
  }
}

在这种情况下,无论发生任何路由或任何状态更改,searchString 值将在整个组件中保持一致

对于此要求:

The idea is that if searchString is null, the API will return all licences (as "/licenses" does), but if the string contains something, it will return only matching licenses.

由于您已经可以访问 searchString,此时您可以根据 searchString 值进行条件语句并评估是否需要 API 到 return是否所有许可证等