従来jsxで書いていたReact.jsのアプリをTypeScriptで書き直したいと思っているのですが、cookieの使い方がわかりません。
js-cookie(従来はこれを利用)など試したりもするのですが、すべてundefinedか空白となります。
設定等に抜けがありそうな気もするのですが、どうでしょうか。
参考
https://developer.mozilla.org/ja/docs/Web/API/Document/cookie
TypeScript
1import * as React from 'react'; 2import * as ReactDOM from 'react-dom'; 3import * as Cookies from "js-cookie"; 4 5document.cookie = "name=oeschger"; 6document.cookie = "favorite_food=tripe"; 7 8function alertCookie() { 9 alert(document.cookie); 10} 11 12class App extends React.Component { 13 setClick(){ 14 Cookies.set('name', 'value', { path: '/' }); 15 }; 16 getClick(){ 17 const name = Cookies.get('name'); 18 alert(name); 19 }; 20 render() { 21 Cookies.set('myCat', 'Pacman', { path: '/' }); 22 alertCookie(); 23 return ( 24 <div> 25 <button type="submit" onClick={() => this.setClick()}>set</button> 26 <button type="submit" onClick={() => this.getClick()}>get</button> 27 </div> 28 ); 29 } 30} 31 32ReactDOM.render(<App/>, document.querySelector('#app'));
json
1// tsconfig 2{ 3 "compilerOptions": { 4 "sourceMap": true, 5 "target": "es5", 6 "module": "es2015", 7 "jsx": "react", 8 "moduleResolution": "node", 9 "lib": [ 10 "es2017", 11 "dom" 12 ] 13 } 14 } 15
json
1//package.json 2{ 3 "name": "tsproj", 4 "version": "1.0.0", 5 "description": "", 6 "main": "index.js", 7 "scripts": { 8 "build": "webpack", 9 "watch": "webpack -w", 10 "test": "echo \"Error: no test specified\" && exit 1" 11 }, 12 "keywords": [], 13 "author": "", 14 "license": "ISC", 15 "devDependencies": { 16 "ts-loader": "^4.4.1", 17 "typescript": "^2.9.2", 18 "webpack": "^4.12.0", 19 "webpack-cli": "^3.0.6" 20 }, 21 "dependencies": { 22 "@types/js-cookie": "^2.1.0", 23 "@types/react": "^16.3.17", 24 "@types/react-dom": "^16.0.6", 25 "es-cookie": "^1.2.0", 26 "js-cookie": "^2.2.0", 27 "react": "^16.4.1", 28 "react-cookie": "^2.1.6", 29 "react-dom": "^16.4.1", 30 "universal-cookie": "^2.1.5" 31 } 32} 33
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/06/20 06:28
2018/06/20 07:48
2018/06/20 09:17