如何根据本地存储重新呈现反应组件?

时间:2020-09-08 17:34:38

标签: reactjs

每次设置新的本地存储项目时如何重新渲染<FormList/>元素?

我有2个同级组件

class App extends React.Component{
  render(){
    <div>
      <MakeForm/>
      <FormList/>
    </div>
  }
}

我想做的只是

  1. <MakeForm/>组件中创建具有多个输入的新表单元素,并将其设置为localstorage(JSON格式)
  2. 获取新的本地存储系统
  3. <FormList/>中为本地存储中的每个项目显示表单名称和按钮

我不知道这是否有帮助,但是我正在使用 react-router-dom 模块。我的<MakeForm/>组件和<FormList/>组件具有不同的URL。

class MakeForm extends React.component{
  constructor(){
    super()
    this.state = {
    //Some properties 
  }
  }
  handleClick= () => {
    //Stringfy state's value and set localstorage item with it
  }
  render(){
    <input type="submit" onClick={this.handleClick} />

  }
}
class FormList extends React.Component{
  //Get the data from localstorage 
  render(){
    <div>
      <p>{/* Form name */}</p>
      <button>{/* Show the form */}</button>
    </div>
  } 
}

一切正常。但是<FormList/>不会重新呈现。我每次制作新表单时都需要刷新页面,以便在主页上看到新的表单元素。

每次设置新的本地存储项目时如何重新渲染<FormList/>元素?

1 个答案:

答案 0 :(得分:0)

我写了一个开源钩子,将class ActivitySettings : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_settings) topToolbarBack.setNavigationOnClickListener { finish() } val frgSettingsMain = FragmentSettingsMain() setCurrentFragment(frgSettingsMain) } private fun setCurrentFragment(fragment: Fragment) = supportFragmentManager.beginTransaction().apply { replace(R.id.framelayoutSettings, fragment) commit() } } 替换为localStorage支持的版本(available here),该版本可以满足您的需求。对于基于类的函数,原理是相同的,只是没有那么干净的抽象:

useState

在您的情况下,您可能希望接受来自localStorage的值作为对const LocalStorage extends React.Component { constructor(props) { super(props) this.state = { value: window.localStorage.getItem(props.key) } } componentDidMount() { window.addEventListener("storage", this.handleChanges) } componentWillUnmount() { window.removeEventListener("storage", this.handleChanges) } handleChanges = e => { // only subscribe to changes to the key specified if (e.key === this.props.key) { this.setState({ value: e.newValue }) } } // Use this instead of `setState` when setting a new value updateValue = newValue => { this.setState({ value: newValue }) window.localStorage.setItem(this.props.key, newValue) } render() { return this.props.children(this.state.value, this.updateValue) } } <LocalStorage key="someProperty"> {(value, setValue) => ( <YourComponent someProperty={value} updateProperty={setValue} /> )} </LocalStorage> 的支持,然后使用setter(FormList)来更新setValue方法中的数据