検索
ホームページウェブフロントエンドフロントエンドQ&A状態の更新に反応するメソッドは何ですか?

反応状態の更新メソッドは次のとおりです。 1. キー、「”; 2. ref 親コンポーネントを使用して子コンポーネント関数を呼び出します。 3. 親を通じてデータを子に渡し、子はレンダリングのみを担当します。

状態の更新に反応するメソッドは何ですか?

#このチュートリアルの動作環境: Windows7 システム、react17.0.1 バージョン、Dell G3 コンピューター。

react で状態を更新する方法は何ですか?

react では、親プロパティが変更されたときに子の状態を更新する方法がたくさんあります。

サブコンポーネント:

class Children extends Component {
  constructor(props) {
     super(props);
     this.state = {
       a: this.props.a,
       b: this.props.b,
       treeData: '',
       targets: '',
     }
    }
  componentDidMount() {
   const { a, b } = this.state
   const data = {a,b}
   fetch('/Url', {
     data
   }).then(res => {
   if (res.code === 0) {
     this.setState({
     treeData: res.a,
     targets: res.b,
  })
  } else {
   message.error(res.errmsg)
  }
  })
  }
 test(item1, item2) {
   const data = { item1, item2 }
   fetch('/Url', {data}).then(res => {
     if (res.code === 0) {
       this.setState({
         treeData: res.a,
         targets: res.b,
       })
     } else {
       message.error(res.errmsg)
     }
   })
 }
}
export default Children

方法 1: キーを上手に使用する

<Children key={this.state.key} a={this.state.a} b={this.state.b} /> //父组件调用子组件

この方法では、キーの変更によってサブコンポーネントが再インスタンス化されます (react でのキーの変更により、コンポーネント) コンポーネント)

方法 2: ref 親コンポーネントを使用してサブコンポーネント関数を呼び出します (反応設計仕様に準拠していませんが、エスケープ出口と見なすことができます)

class father extends Component {
    constructer(props) {
      super(props);
      this.state={
       a: &#39;1&#39;,
       b: &#39;2&#39;,
      }
      this.myRef
      this.test = this.test.bind(this)
    }
   change() {
     const { a,b } = this.state
     console.log(this.myRef.test(a,b)) // 直接调用实例化后的Children组件对象里函数
    }
render() {
 <Children wrappedComponentRef={(inst) => { this.myRef = inst } } ref={(inst) => { this.myRef = inst } } />  
 <button onClick={this.test}>点击</button>
}
}

注: WrappedComponentRef は、react-router です。上位コンポーネントが ref を正しく取得できない問題を解決するために v4 で使用されます (非上位コンポーネントを削除する必要があります)

方法 3: 親データを子に渡し、子はレンダリングのみを担当します (反応設計の概念に最も一致しています))推奨! !

親コンポーネント:

class father extends Component {
    constructer(props) {
      super(props);
      this.state={
       a:&#39;1&#39;,
       b:&#39;2&#39;,
       data:&#39;&#39;,
      }
    }
  getcomposedata() {
    const { a, b } = this.state
    const data = { a, b }
    fetch(&#39;/Url&#39;, {data}).then(res => {
      if (res.code === 0) {
        this.setState({
          data:res.data
        })
      } else {
        message.error(res.errmsg)
      }
    })
  }
render() {
 <Children data={this.state.data}} />  
}
}

子コンポーネント:

  componentWillReceiveProps(nextProps) {
    const { data } = this.state
    const newdata = nextProps.data.toString()
    if (data.toString() !== newdata) {
      this.setState({
        data: nextProps.data,
      })
    }
  }

注意: ReactのcomponentWillReceivePropsサイクルが存在期間であり、変更されたpropsは自身の状態の判断と更新に使用されます

推奨される学習: 「

react ビデオ チュートリアル

以上が状態の更新に反応するメソッドは何ですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
USESTATEの理解():React React Neact State Managementの包括的なガイドUSESTATEの理解():React React Neact State Managementの包括的なガイドApr 25, 2025 am 12:21 AM

usestate()isareacthookusedtomeStateinfunctionalComponents.1)itInitializeSandUpDatestate、2)colledatttheToplevelofComponents、3)canleadto'stalestate'ifnotusedly、and4)cancancancancancanbeoptimizeduptimizeduptimizedususecall -calleSuperesteSteSteSteSteSteSteSteSteStateSupteStateSuptateSuptatedates

Reactを使用することの利点は何ですか?Reactを使用することの利点は何ですか?Apr 25, 2025 am 12:16 AM

ReactisPopularduetoitsComponent Architecture、Virtualdom、Richecosystem、およびdeclarativenature.1)コンポーネントベースのarchitectureallowsforReusable anduipieces、改善様式および測定可能性。

Reactでのデバッグ:一般的な問題の特定と解決Reactでのデバッグ:一般的な問題の特定と解決Apr 25, 2025 am 12:09 AM

debugReactapplicationivivivity、EtheseStrategies:1)AddressPropdrillingWithContextapiorredux.2)HandLeasynchronousoperations withuthutateanduseeffect、Abortcontrollertopreventraceconditions.3)最適化合物を使用して、最適化合物を使用してください

ReactのUseState()とは何ですか?ReactのUseState()とは何ですか?Apr 25, 2025 am 12:08 AM

UseState()inReactallowsstateManagementInFunctionalComponents.1)itsimplifiesstateManagement、makeCodemoreconcise.2)usetheprevcountFunctionToupDateStateBasedTateBasedTateBadeStateValue、AvolidingStalestateSues.3)

useState()vs。usereducer():州のニーズに合った適切なフックを選択するuseState()vs。usereducer():州のニーズに合った適切なフックを選択するApr 24, 2025 pm 05:13 PM

ChooseuseState()forsimple,independentstatevariables;useuseReducer()forcomplexstatelogicorwhenstatedependsonpreviousstate.1)useState()isidealforsimpleupdatesliketogglingabooleanorupdatingacounter.2)useReducer()isbetterformanagingmultiplesub-valuesorac

UseState()を使用して状態を管理する:実用的なチュートリアルUseState()を使用して状態を管理する:実用的なチュートリアルApr 24, 2025 pm 05:05 PM

UseStateは、州の管理を簡素化し、コードをより明確にし、読みやすくし、Reactの宣言的な性質と一致するため、クラスコンポーネントやその他の州管理ソリューションよりも優れています。 1)UseStateを使用すると、状態変数を関数コンポーネントに直接宣言することができます。2)フックメカニズムの再レンダリング中に状態を覚えています。

UseState()を使用する時期と、代替の州管理ソリューションを検討するタイミングUseState()を使用する時期と、代替の州管理ソリューションを検討するタイミングApr 24, 2025 pm 04:49 PM

useUsestate()forlocalcomponentStatemanagement; compleartinative forglogic、orperformanceissues.1)useidealforsimple、localstate.2)useglobalStateSolutionSolutionSuxorContextForSharedState.3)OptForreDuxtormobxobxobxobforexSt

Reactの再利用可能なコンポーネント:コードの維持可能性と効率の向上Reactの再利用可能なコンポーネント:コードの維持可能性と効率の向上Apr 24, 2025 pm 04:45 PM

再利用することは、codecodemaintainabilityを抑制することを再生します

See all articles

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強力な PHP 統合開発環境

SublimeText3 英語版

SublimeText3 英語版

推奨: Win バージョン、コードプロンプトをサポート!

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Eclipse を SAP NetWeaver アプリケーション サーバーと統合します。

WebStorm Mac版

WebStorm Mac版

便利なJavaScript開発ツール