簡體   English   中英

在分離的反應組件之間共享 state

[英]Share state between separated react components

我是新的 React 用戶,我正在嘗試從組件 A function 中獲取組件 B 中的值。 我不知道是否有可能以這里介紹的簡單方式獲得價值。 我在 B 中的代碼類似於:

import React, { Component } from 'react';

class B extends Component { 
    constructor(props){
        super(props)
        this.state = { 
            value: 0
        }
    }

    setValue = async(newValue) => {
        this.setState({value: newValue})
    }

    getValue = async() => {
        return this.state.value
    }

    render() {
     return(
       <div className = "flex justify-center">
                <div className = "w-1/2 flex flex-col pb-12">
                    <form onSubmit={(event) => {
                        event.preventDefault()
                        const value = this.value.value
                        this.setValue(value)
                    }}>

                        <input type="text"
                            className="form-control mb-1"
                            placeholder="New Value"
                            ref={(input) => this.value= input} />

                        <input type="submit"
                            className="bbtn btn-block btn-primary btn-sm"
                            value="Set Value" />
                    </form> 
                </div>  
            </div>
    )}
} export default B

我在 A 組件中嘗試做的是:

import React, { Component } from 'react';
import './B'

class A extends Component { 

    getValue = async() => {
        const valueInB = B.getValue()
        console.log("Value in B is: ", valueInB);
    }

    render(){
        return(
             <form onSubmit={(event) => {
                    event.preventDefault()
                    this.getValue()
                }}>

                    <input type="submit"
                        className="bbtn btn-block btn-success btn-sm"
                        value="Get Value" />
                </form>
        )
    }

} export default A

我知道 getValue() function 中的代碼是錯誤的,但這是一種顯示我想在 A 組件中獲得的值的方法。

為了在這里提供最佳答案,我們需要考慮兩個組件之間的關系。

例如,如果兩個組件最終由單個父組件呈現,那么管理此問題的一種簡單方便的方法是簡單地將state移動到父組件,並將其作為 props 與setState方法一起傳遞給子組件或專用處理相關邏輯的函數。

例子:

class Parent extends Component {
    constructor(props) {
        super(props)
        this.state = { 
            value: 0
        }
    }

   return (
      <A state={this.state} setState={this.setState} />
      <B state={this.state} setState={this.setState} />
   )
}

但是,如果不是這樣,而且它們之間的關系更加復雜,
那么您可能需要管理一些全局 state。
這可以通過 React 的內置上下文 Api或通過第三方 state 管理庫(例如ReduxxState )來實現

Context API 是最簡單的解決方案,因為它是 React 本身的一部分。

  1. 將共享數據及其修改器方法存儲在最頂層組件的 state 中。
  2. 在最頂層的組件中,通過Provider渲染 state。
  3. 在需要此共享數據的組件中,呈現Subscriber ,並訪問/修改數據。

教程非常有用,因為它通過示例描述了基於 class 和 function 組件的過程。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM