更改父组件的状态后,子组件的重新渲染正在使用类,但不适用于钩子

时间:2021-05-25 19:45:48

标签: react-native react-hooks

请帮我解决这个问题:有“箭头”组件会改变父组件的父组件的状态。一般父级的状态影响渲染它的子级。当我使用类时,我的应用程序运行良好。但是,如果我尝试使用 Hooks,它会出乎意料地工作:一般父级的状态会立即更改,但不会执行重新渲染子级。你能告诉我有什么问题吗? (代码已经简化)

带类:

//general parent component

export default class Container extends React.Component {
    constructor(props) {
        super(props);
        this.state = { page: 5 };
        this.nextPage = this.nextPage.bind(this);
    }
    nextPage() {
            let currentPage = this.state.page;
            this.setState({ page: currentPage +1});
        }
    render() {
        return (
                 <List 
                     onPageUp={this.nextPage}
                     statePage={this.state.page}
                 />
               );
        }
    }

//child
export default class List extends React.Component {
    constructor(props) {
        super(props);
    }

render() {
        const thisPage = this.props.statePage;
        /*here's the calculations depending on thisPage*/
        return (
            <View>
               <ArrowRight onPageUp={this.props.onPageUp} />
               <SomeView />
            </View>
          );
      }
}


//right arrow - child of the child
export default class ArrowRight extends React.Component {
    constructor(props) {
        super(props);
    }

    render() {
        return (
            <View>
                <TouchableOpacity
                    onPress={() => this.props.onPageUp()}
                >                    
                </TouchableOpacity>
            </View>

        )
    }
}

带钩子:

//general parent component
export default function Container() {
    const [page, setPage] = useState(5);
    
    const nextPage = () => {
        let currentPage = page;
        setPage(currentDate + 1);
    }

    return (
        <View>
            <List
                statePage={page}
                nextPage={nextPage}                
            />    
       </View>
    );
}

//child
export default function List (props) {
     
    const thisPage = props.statePage;
    /*here's the calculations depending on thisPage*/
    return (
        <View>
           <ArrowRight nextPage={props.nextPage} />
           <SomeView />
        </View>
}

//right arrow - child of the child
export default function ArrowRight(props) {
        return (
            <View>
                <TouchableOpacity
                    onPress={() => props.nextPage()}
                >          
                </TouchableOpacity>         
            </View>
        )
}

0 个答案:

没有答案