反应本机模态错误评估 _this5.state.error[key]

React native modal error evaluating _this5.state.error[key]

我还是 React Native 的新手,我正在尝试使用计时器制作模态,但我收到一条错误消息,说未定义不是一个对象(正在评估“_this5.state.error[key]”)我试过了用 setTimeout() 打开模态,我认为它的状态有问题,有人有办法解决它吗?谢谢

这是我的代码

class FormInput extends Component {

    constructor(props) {
        super(props);

        const { fields, error } = props;

        this.state = this.createState(fields, error);

        this.state = {
            visible: false
        }

        //bind functions
        this.onChange = this.onChange.bind(this);
        this.onSubmit = this.onSubmit.bind(this);
    }

    componentDidMount(){
        this.timer = setTimeout(this.showModal, 5000); //auto reset after 60 seconds of inactivity
    }

    componentWillUnmount(){
        clearTimeout(this.timer);
    }

    showModal() {
        this.setState ({ visible: true})
    }

    closeModal() {
        this.setState ({ visible: false})
    }
    
        createState(fields, error) {
        const state = {};
        fields.forEach((field) => {
            let { key, type, value, mandatory } = field;
            state[key] = { type: type, value: value, mandatory: mandatory };
        })

        state["error"] = error;
        state["submitted"] = false;

        return state;
    }

    
    
    render() {

        return (
                <View>
                    <AlertModal visible={this.showModal} close={this.closeModal}/>
                    </View>

        );

将 showModal 声明为箭头函数

showModal = () => {
  this.setState ({ visible: true})
}

或为 showModal

绑定上下文
this.timer = setTimeout(this.showModal.bind(this), 5000)

this.timer = setTimeout(() => {this.showModal()}, 5000)

learn more about javascript context this

使 showModalcloseModal 成为箭头函数

showModal = () => {
  this.setState ({ visible: true })
}

closeModal = () => {
  this.setState ({ visible: false })
}

或在构造函数中绑定它们。

另外 visible prop 是一个布尔值,你正在传递一个函数。通过 this.state.visible 以解决问题。

<AlertModal visible={this.state.visible} close={this.closeModal} />

--- 已更新 ---

所以在检查了您更新后的代码后,我能够找出问题所在。在构造函数中你正在这样做

        this.state = this.createState(fields, error);

        this.state = {
            visible: false
        }

覆盖 this.state。所以我建议你将 visible: false 移动到 createState 函数中并将其从构造函数中删除。