![](/img/trans.png)
[英]Pass parameter to same function and receive different date and pass it to props
[英]is it possible, to get a props and pass it as a parameter to a function?
我正在嘗試通過 react-redux 的連接從 MapsStateToProps 獲取道具,然后將其傳遞給子組件。 這個 prop 被用作函數的參數,函數負責返回一些東西,然后一些東西成為子組件的狀態。
我知道道具正在更新,因為我將它顯示在子組件中,但是在它用作參數的地方它不會立即更新。 我必須導航到另一個組件(react-routers),然后返回到原始組件以查看使用 props 的函數結果所需的結果。
有沒有辦法在不轉到另一個組件然后返回的情況下進行更改? 顯然我做錯了什么,或者我想做的不是反應方式? 有小費嗎?
import React, { Component } from 'react';
import {connect} from "react-redux";
import filterData from "../../States/AllStates/filterData"
import BookComponent from "./BookComponent";
const mapStateToProps = state => {
return {
fmlProps: state.ReducerName.fmlProps
}
};
class Testing extends Component {
state = {
// this.props.fmlPropsdoesn't work right away. You need to go away then come back
// to see the desired result, which I want to avoid
XXX: filterData(this.props.fmlProps)
}
render() {
return (
<>
<h1>{this.props.fmlProps}</h1> {/* this show up correct */}
{this.state.XXX.map(FakeData => (
<BookComponent
key={FakeData.planNumber}
PNum={FakeData.planNumber}
PName={FakeData.planName}
/>))}
</>
);
}
}
export default connect(mapStateToProps, null) (Testing);
使用 componentDidUpdate 檢查並在組件更新時調用函數。
componentDidUpdate(prevProps) {
// Typical usage (don't forget to compare props):
if (this.props.fmlProps !== prevProps.fmlProps) {
//invoke function and setstate
const tmp = XXX: filterData(this.props.fmlProps)
this.setState({XXX})
}
}
更多閱讀在這里 - https://reactjs.org/docs/react-component.html#componentdidupdate
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.