🦾
React逆引きガイド (6/100)
Reactのバージョンは16.13.1です。
徐々に足していきます。
Fragmentを<>で書いているがkeyを設定したい
// hmmm
<key={anyVariable}></>
// good
<Fragment key={anyVariable}></Fragment>
レンダリング毎ではなくcomponentDidMountとしてuseEffectで処理を書きたい
const [didMount] = useState('didMount');
useEffect(() => {
console.log('mounted');
}, [didMount])
Propsにデフォルト値を設定したい
const defaultProps = {
fuga: 'defaultValue'
}
const HogeComponent = (props) => {
return (
<div>{props.fuga}</div>
)
};
HogeComponent.defaultProps = defaultProps;
export default HogeComponent;
参考: https://github.com/facebook/react/issues/16905
useStateで配列を扱いたい
const [hogeStates, setHogeStates] = useState([]);
// 追加
setHogeStates([...hogeStates, newValue]);
// 削除
setHogeStates(hogeStates.filter(hogeState => hogeState !== targetValue ));
importする時に../../../../を辞めたい
ルートにtsconfig.jsonまたはjsconfig.jsonを作成し"compilerOptions"の"baseUrl"と"include"に'src'を追加するとsrcから指定できる。
// tsconfig.jsonの場合
{
"compilerOptions": {
~~~~
"baseUrl": 'src'
},
"include": ['src']
}
// hmmmm...
import '../../../../../components/Hoge/';
// good
import 'components/Hoge/';
CSSファイルでurlを指定する時にurl(../../../../)を辞めたい
~
を使うとsrcから指定できる。
// hmmmm...
.hoge {
background-image: url('../../../../../../../assets/img/fuga.png');
}
// good
.hoge {
background-image: url('~assets/img/fuga.png');
}
Discussion