最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React Setting State from another file - Stack Overflow

programmeradmin2浏览0评论

I have a function which I'm going to use in a lot of screens and I don't want to copy-paste it in every screen ponent so I created a new ponent inputValidation.js and put the function there

export function validate(text,type) {
    emailPattern=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
    if (type=='username'){
        if (emailPattern.test(text)){
            setState({ validUsername: true })
        } else {
            setState({ validUsername: false })
        }
    }
    if (type=='password'){
        if (text.length < 8){
            this.setState({ validPassword: false })
        } else {
            this.setState({ validPassword: true })
        }
    }
}

and I imported it in my screen ponent like this loginScreen.js

export default class LoginScreen extends Component {
    static navigationOptions = { header: null };
    constructor(props) {
        super(props)
        this.state = {
            username: '',
            validUsername: false,
            password: '',
            validPassword: false,
        };
    }

    render() {
        return (
            <Container style={styles.container}> 
                <View style={{ flex: 1, justifyContent: 'space-between'}}>

                    <Item style={styles.inputContainer} success={this.state.validUsername ? true : false} bordered regular>

                        <Input
                        onChangeText={(text) => validate(text,'username')}
                        autoCapitalize="none" 
                        autoCorrect={false}
                        style={styles.input} 
                        placeholder='Email' />

                        <Icon style={styles.inputIcon, !this.state.validUsername ? styles.inputIconHidden : null} type='Entypo' name='check' />

                    </Item>
                </View>

          </Container>
        )
    }
}

but I get error can't find variable: setState

I am new to react native so what's wrong ? it was working just fine before I copy-paste the function on another file

I have a function which I'm going to use in a lot of screens and I don't want to copy-paste it in every screen ponent so I created a new ponent inputValidation.js and put the function there

export function validate(text,type) {
    emailPattern=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
    if (type=='username'){
        if (emailPattern.test(text)){
            setState({ validUsername: true })
        } else {
            setState({ validUsername: false })
        }
    }
    if (type=='password'){
        if (text.length < 8){
            this.setState({ validPassword: false })
        } else {
            this.setState({ validPassword: true })
        }
    }
}

and I imported it in my screen ponent like this loginScreen.js

export default class LoginScreen extends Component {
    static navigationOptions = { header: null };
    constructor(props) {
        super(props)
        this.state = {
            username: '',
            validUsername: false,
            password: '',
            validPassword: false,
        };
    }

    render() {
        return (
            <Container style={styles.container}> 
                <View style={{ flex: 1, justifyContent: 'space-between'}}>

                    <Item style={styles.inputContainer} success={this.state.validUsername ? true : false} bordered regular>

                        <Input
                        onChangeText={(text) => validate(text,'username')}
                        autoCapitalize="none" 
                        autoCorrect={false}
                        style={styles.input} 
                        placeholder='Email' />

                        <Icon style={styles.inputIcon, !this.state.validUsername ? styles.inputIconHidden : null} type='Entypo' name='check' />

                    </Item>
                </View>

          </Container>
        )
    }
}

but I get error can't find variable: setState

I am new to react native so what's wrong ? it was working just fine before I copy-paste the function on another file

Share Improve this question edited Nov 8, 2019 at 14:59 glinda93 8,4996 gold badges50 silver badges87 bronze badges asked Nov 8, 2019 at 14:47 mohamed adelmohamed adel 7153 gold badges15 silver badges38 bronze badges 1
  • 1 in the function file, the reference to this is different from your ponent's so one thing you can do is, pass this reference to your function file, or you can call the function and set the state in the ponent ( which is the ideal solution ). – Partha Roy Commented Nov 8, 2019 at 14:52
Add a ment  | 

2 Answers 2

Reset to default 4

Just setState alone makes no sense (and it never should have worked) because it's an instance function. Since it's an instance function it also won't work because this will be (roughly) meaningless out of a class instance context.

You could pass the setState function along, but that's a road to despair.

Since this is tied to username and password fields you should just have a separate ponent you bring in to the pages.

If that doesn't work then separate the concerns of "validation" and "what to do with validation results" and don't tie validation to a specific implementation of the validation process.

I think you might be able to do something like this:

constructor(props) {
    super(props);
    this.state = {
        username: '',
        validUsername: false,
        password: '',
        validPassword: false,
    };
    this.validate = validate.bind(this);
}

...


              <Input
                onChangeText={(text) => this.validate(text,'username')}

This should make it so that inside the validate function, this is bound to your React ponent and this.setState() thus has a meaning and context.

发布评论

评论列表(0)

  1. 暂无评论