react踩坑记录

input的只读模式

<Input readOnly />  

注意:是readOnly,readonly或readonly=”readonly”无效。

绑定的函数在加载时就会马上执行,不是触发才执行 
写法规范例子:

不会马上执行:
<div onClick={ handlerClick }>点击我呀!</div>
有传入参数,加载时马上执行:
<div onClick={ handlerClick(i) }>点击我呀!</div>
解决方法:
<div onClick={ ()=>{ handlerClick(i) } }>点击我呀!</div> 

不带毫秒数的时间戳 
format前要先unix为标准格式, moment.unix(int类型)。 
多个时间方法调用:

const formatDate = (timeTs, formatter = 'YYYY-MM-DD HH:mm:ss') => (
    !timeTs ? '' : moment.unix(parseInt(timeTs, 10)).format(formatter)
);
const planEndTime=formatDate(stateSit.planEndTime);

Error: must set key for children 
在使用antd-design中的select的组件时候,报这样的错误。 
原因:在select中设置了多选mode = ‘multiple’,并把initialValue或value的值设为了[”]; 
解决方法:initialValue或value值设为空[],或不为空的字符串[“xxx”];

Warning: getFieldDecorator will override value, so please don’t set value directly and use setFieldsValue to set it. 
在使用antd-design中的From组件用getFieldDecorator方式的时候,报这样的警告。 
原因:因为我们在自定义组件中定义了value、defaultValue值,getFieldDecorator会覆盖我们定义的值; 
解决方法:不能用控件的 value defaultValue 等属性来设置表单域的值,默认值可以用 getFieldDecorator 里的 initialValue;

页面跳转传参,this.props.location.query和this.props.location.state的区别 
this.props.location.query:跳转后的url中含有传过来的信息;无跳转刷新页面的时候,无需判断是否有传参。 
this.props.location.state:跳转后的url中不含有传过来的信息;无跳转刷新页面的时候,需要判断是否有传参,否则容易报错。

数组的push和concat方法 
push:将一个对象添加到某数组的最后。 
concat:两个或多个数组拼接用,将数组添加到某数组的最后,不会过滤掉重复值。

var arr = [1,2,3];
arr = arr.concat( [ 4,5,6,3] ); 
console.log( arr ); // 输出 [1,2,3,4,5,6,3];

如果你的环境支持 ES6还可以用 ... 

var arr = [ 1,2,3, ...arr2 ];
或者 

var arr = [ 1, 2, 3 ];
arr.push( ...[ 4, 5, 6 ] );

将数组按照某个属性进行分类显示,groupBy 与map合作 
groupBy :http://www.css88.com/archives/7774 
项目实际代码段:

import { groupBy } from 'lodash';
const userContent = stateSit.participants ? Object.values(groupBy(stateSit.participants, 'teamId'))
        .map((men, i) => `${men[0].team}:${men.map(({ employeeId, employeeName }, idx) => employeeName).join(',')}`)
        .join(';') : null;

不要轻易用Async/Await调戏React的生命周期componentWillMount 
Async/Await是异步执行,而componentWillMount我个人认为是同步执行,改为异步的话,虽然不会造成阻塞,但会影响页面数据渲染。比B是由生命周期里的A计算得出的,A却是异步获取的,这样逻辑就不通,因为A正在发送请求的同时,B已经开始执行计算了。应该将A改为callback获取结果。

  • 4.Warning: setState(...): Cannot update during an existing state transition (such as within render or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to componentWillMount。当报这类错误时,说明你的props和states在渲染的时候更改了。

大体意思就是在render这种需要props和state进行渲染的方法中,不能再对props和state进行更新。我的理解是,React会在props和state改变的时候调用 render进行DOM diff然后渲染,如果在渲染过程中再对props和states进行更改,就陷入死循环了。
例如:
<Button onPress={hideMessage('隐藏信息')}>隐藏信息</Button>
当点击button时,就会报上述错误,因为这样会在渲染是更改组件的状态。
解决方法:
在调用方法时创建一个匿名函数,再调用。
<Button onPress={()=>{hideMessage('隐藏信息')}}>隐藏信息</Button>

  • 5.组件<Image source={...} /> 当图像资源来自网络时不显示图片。

当使用<Image />source属性时,从网络获取图片资源,要求设置图片的高度和宽度。FB react native文档上并没有提示这点。

猜你喜欢

转载自blog.csdn.net/u010565037/article/details/88551825