为什么我的localStorage.setItem似乎什么都没做?

时间:2019-02-01 21:42:34

标签: javascript reactjs local-storage

我试图将代码简化为相关的代码。

import sys
import socket
import getopt

def usage(script_name):
    print('Usage: py' + script_name + '-l' +' <port number>' + '[<server>]')

def sockObj():
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    return sock

def serversockConn(serversocket,port):
    serversocket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
    # bind the serversocket to address
    serversocket.bind(('',int(port)))
    # enable a server to accept connections
    serversocket.listen(5)
    # wait for a connection and accept it
    sock,addr = serversocket.accept()
    return sock

def connToServersock(sock,server, port):
    # connect to a serversocket
    if server:
        sock.connect((server, int(port)))
    else:
        sock.connect(('localhost', int(port)))
    return sock

if __name__ == '__main__':
    ## get the command line arguments
    try:
        options, non_option_args = getopt.getopt(sys.argv[1:],'l')
    except getopt.GetoptError as err:
        print(err)
        sys.exit(2)

    #check if '-l' is present in command line agrument
    serverSide = False
    for opt,arg in options:
        if opt == "-l":
            serverSide = True

    # port number
    port = non_option_args[0]

    # server address
    server = None
    hostLen = len(non_option_args)
    if hostLen == 2:
        server = non_option_args[1]


    # create a communicator object, and make a connection between server and client

    # server
    if serverSide:
        serversocket = sockObj()
        sock = serversockConn(serversocket,port)
    # client
    else:
        sock = sockObj()
        sock = connToServersock(sock,server,port)

    while True:
        ## read a message from standard input
        message = sys.stdin.readline().encode()
        if len(message) != 0:
            sock.send(message)
            return_msg = sock.recv( 1024 )
            if return_msg:
                print("Message recieved: " + return_msg.decode())
            else:
                print("Other side shut down")
        else:
            try:
                sock.shutdown(socket.SHUT_WR)
                sock.close()
            except:
                pass

本质上,我的网页上有一个表单组件,提交时将执行this.handleSubmit,并且该函数位于底部。

我的代码应该做的是使用键“ user”将提交的字符串保存到localStorage,但是显然没有(您可以在console.log输出中看到)。

知道发生了什么吗?

enter image description here

我的网站在本地托管,通过隧道传送到URL,并用作shopify嵌入式应用程序的基本URL,只是为了提供所有相关上下文。

更新

class AnnotatedLayout extends React.Component {
    state = {
        user: '',
        enabled: false,
    };

    render() {
        const { user, enabled } = this.state;
        const contentStatus = enabled ? 'Disable' : 'Enable';
        const textStatus = enabled ? 'enabled' : 'disabled';

        return (
            ...
                            <Form onSubmit={this.handleSubmit}>
                                <FormLayout>
                                    <TextField
                                        value={user}
                                        onChange={this.handleChange('user')}
                                        label="Shop Name"
                                        type="user"
                                        helpText={
                                            <span>
                                                Log in with your store username.
                                            </span>
                                        }
                                    />
                                    <Stack distribution="trailing">
                                        <Button primary submit>
                                            Submit
                                        </Button>
                                    </Stack>
                                </FormLayout>
                            </Form>
                        ...
        );
    }
    handleSubmit = () => {
        this.setState({
            user: this.state.user
        });
        localStorage.setItem('user', JSON.stringify(this.state.user));
        console.log('submission', this.state);
        console.log(this.state.user);
    };
    handleChange = field => {
        return value => this.setState({ [field]: value });
    };
}

export default AnnotatedLayout;

检查一下,现在提交我的文本表单后,这就是我得到的

enter image description here

localStorage是否类似于local或其他东西,以至于它不会在函数之外保存任何内容?

2 个答案:

答案 0 :(得分:0)

似乎您handleChange返回了一个方法,您需要再次调用该方法来设置用户值。

代替

<TextField
   value={user}
   onChange={this.handleChange('user')}
...

尝试

<TextField
   value={user}
   onChange={e => this.handleChange('user')(e)}
...

value中的handleChange应该接受e事件值,这是要设置的用户值。

答案 1 :(得分:-1)

/objects