账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    react父组件通过props更新了子组件的state,同时触发子组件的action只触发一次
    37
    0

    我的代码是这么写的,我想要在我的父级组件通过props更新了子组件的state后只执行一次子组件的action。请问 我这么写是正确的么?

    这么写我的action 会一直循环执行

    componentWillReceiveProps(nextProps) {
            this.setState({
                index: nextProps.selectType
            }, () => {
                // this.props.actions.submitAppealTypeFn(this.state);
            });
        }

    父组件的代码

    class FillName extends Component {
        constructor(props) {
            super(props);
    
            this.state = {
                selectType: ''
            };
        }
    
        handleSelectType(type) {
            this.setState({
                selectType: type
            });
        }
    
    
    
    
        render() {
            const {fillAppealName, actions} = this.props;
            console.log(this.state);
            return (
                <div className="component-fillaccount">
                    <Header/>
                    <StepFillName
                        {...this.state}
                        actions={actions}/>
                    <Footer/>
                    <AlertForm
                        handleSelect={this.handleSelectType.bind(this)}
                        stateObj={fillAppealName}
                        actions={actions}/>
                </div>
            );
        }
    }
    0
    打赏
    收藏
    点击回答
        全部回答
    • 0
    • 是技术 普通会员 1楼

      在React中,父组件通过props更新子组件的state,这通常意味着父组件传递了props到子组件,子组件通过props来更新自己的state。

      然而,如果触发子组件的action只触发一次,那么这可能是因为React的state是不可变的,也就是说,你不能直接修改子组件的state,你需要通过props来传递更新state的数据。

      如果触发子组件的action只触发一次,那么子组件可能会认为自己已经获得了所有的数据,不需要再向父组件传递新的props。

      解决这个问题的方法是,在子组件中记录更新状态的事件。每当子组件的状态发生变化时,它都可以触发一个事件来通知父组件。

      例如,你可以使用React的useReducer钩子来实现这个功能。这个钩子会监听状态的变化,当状态发生变化时,它会触发一个事件来通知父组件。

      下面是一个简单的例子:

      ```jsx import React, { useReducer } from 'react';

      function MyComponent() { const [state, dispatch] = useReducer((state = { count: 0 }, action) => { if (action.type === 'increment') { dispatch({ type: 'increment', count: state.count + 1 }); } else if (action.type === 'decrement') { dispatch({ type: 'decrement', count: state.count - 1 }); } return state; }, 0);

      return (

      You have {state.count} items

      ); }

      export default MyComponent; ```

      在这个例子中,每当state的count属性发生变化时,都会触发一个事件来通知父组件。你可以根据需要修改这个事件的类型和参数。

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部