Reac全家桶笔记

待学习:

react官网看三遍: 第一遍大致完成,待查漏补缺

react-router官网文档看一遍:尚未开始

react-redux看三遍:已看第一遍!待查漏补缺 

react源码研读尚未开始

 

reactRouter: matchPathwithRouter

 

 react进阶:https://www.cnblogs.com/ycxqdkf/p/13375019.html

 

 

 

Action中获取store:

 

属性传递方式: 1.使用Context(谨慎使用) 2.组件本身作为属性传递 3.react-redux方式

 

组件懒加载:

const OtherComponent = React.lazy(() => import('./OtherComponent'));

function MyComponent() {

  return (

    <div>

      <Suspense fallback={<div>Loading...</div>}>

        <OtherComponent />

      </Suspense>

    </div>

  );

}

 

 

React开发流程:1.根据单一功能原则拆分组件 2.初步确定每个组件有哪些数据需要存放在state 3.找到那些组件间共享的state,把他们转移到他们共同的父组件去(没有就新建一个共同父组件)  4.复杂页面自下而上编写组件,简单页面反之 (具体每一步如何操作见下放或React官方文档)

 

组合: 通过props.children拿到所有子元素

function Container(props) {

  return (

    <div className={'FancyBorder FancyBorder-' + props.color}>

      {props.children}

    </div>

  );

}

< Container > JSX 标签中的所有内容都会作为一个 children prop 传递给 Container组件。

Props 和组合为你提供了清晰而安全地定制组件外观和行为的灵活方式。注意:组件可以接受任意 props,包括基本数据类型,React 元素以及函数。

 

组件拆分:单一功能原则来判定组件的范围。也就是说,一个组件原则上只能负责一个功能。如果它需要负责更多的功能,这时候就应该考虑将它拆分成更小的组件。

 

自下而上意味着从最基本的组件开始编写(比如 ProductRow)。当你的应用比较简单时,使用自上而下的方式更方便;对于较为大型的项目来说,自下而上地构建,并同时为低层组件编写测试是更加简单的方式。

 

检查相应数据是否该存在 state里:

1.该数据是否是由父组件通过 props 传递而来的?如果是,那它应该不是 state

2.该数据是否随时间的推移而保持不变?如果是,那它应该也不是 state

3.你能否根据其他 state props 计算出该数据的值?如果是,那它也不是 state

 

 

如何判断某个state应该属于哪个组件:

1.找到根据这个 state 进行渲染的所有组件。

2.找到他们的共同所有者(common owner)组件(在组件层级上高于所有需要该 state 的组件)。

3.共同所有者组件或者比它层级更高的组件应该拥有该 state

4.如果你找不到一个合适的位置来存放该 state,就可以直接创建一个新的组件来存放该 state,并将这一新组件置于高于共同所有者组件层级的位置。

 

 

this.setState((state, props) => ({

  counter: state.counter + props.increment

}));

 

Babel 会把 JSX 转译成一个名为 React.createElement() 函数调用

以下两种示例代码完全等效:

const element = (

 <h1 className="greeting">

    Hello, world!

 </h1>

);

const element = React.createElement(

 'h1',

 {className: 'greeting'},

 'Hello, world!'

);

 

所有 React 组件都必须像纯函数一样保护它们的 props 不被更改

 

Render prop:

方式一:使用属性:尽管之前的例子使用了 render,我们也可以简单地使用 children prop

<Mouse children={mouse => (

 <p>鼠标的位置是 {mouse.x}{mouse.y}</p>

)}/>

Mouse组件的声明中:

  render() {

    return (

      <div style={{ height: '100%' }} onMouseMove={this.handleMouseMove}>

        {this.props.children(this.state)}

      </div>

    );

  }

方式二:children prop 并不真正需要添加到 JSX 元素的 “attributes” 列表中。相反,你可以直接放置到元素的内部

<Mouse>

 {mouse => (

    <p>鼠标的位置是 {mouse.x}{mouse.y}</p>

 )}

</Mouse>

 

 

React生命周期:

 

index.js:2178 Warning: You cannot set a form field before rendering a field associated with the value.  报错解决:使用setFields代替setFieldsValue即可

 

 

 

Acton中拿到任何state, 使用: store().get(‘stateName’)

export const getAllversions = callback => (dispatch, store) => {

 console.log('store.getstore():', store().get('version_list'));

 

 

 

表格多行传参:

 

 

 

antd表单排版使用formItemLayout结合RowCol栅格布局,既方便对齐还能实现响应式!

constformItemLayout = {

 labelCol: {

 xs: { span:24 },

 sm: { span:8 }

 },

 wrapperCol: {

 xs: { span:24 },

 sm: { span:16 }

 }

 };

 

 

app组件中拿到共用信息,然后通过属性都传递进去,节约请求数

 <Route

 path="/bus_category"

 render={() => <BUSCategory{...appProps}/>}

 />

 

了解connect()中最后两个参数的作用:

exportdefault connect(

 mapState,

 mapDispatch,

 undefined,

 {

 pure: false

 }

)(App);

 

 

函数作为无状态组件的使用:

const EllipsisTdContent = ({ text, width }) => {

 return (

 <div className="td-div" style={{ width }}>

 <span className="text-overflow" title={text}>

 {text}

 </span>

 </div>

 );

};

 

 

class calc{static count=10;

类成员的静态属性我们可以直接调用,调用方式为如上例的count的调用方式:calc.count。而不能用this.count在类的内部使用。定义了static属性的class不能用new实例化??

 

let list: number[] = [1, 2, 3]; 等价于 let list: Array<number> = [1, 2, 3];

 

classNames库的使用:

<a classNames('foo1', { foo2: false, bar: true }); // => 'foo1 bar'

></a>

 

 

exportclass MigrateDialogextends React.Component<any, IDialogState> {

如上: <>中,any约束this.props的类型,IDialogState约束this.state的类型

 

1.       函数本身可以作为无状态组件被调用

2.       属性就是参数,调用方法: <Hello name='joe’ />

 

console的调试:右键菜单和copy()

 

使用fetchget请求的都要设置带上cookie,因为fetch请求默认不会带cookie!
    credentials: 'include',
(这样就会带上cookie
    mode: 'cors'

 

 

路由中设置可选参数

React-router2.0 :

path="/Login(/:router)"

<Routepath="/Login(/:router)" Component={Login} />

React-router4.0:

path="/Login/:router?"

<Route path="/Login/:router?" Component={Login}/>

 

 

 

 

 componentWillReceiveProps(props) {

 let tmpObj = {};

 if (props.directory_list.length > 0) {

 props.directory_list.forEach((item, index) => {

 tmpObj[`check_${index}`] = item.selected;

 });

 this.setState({

 switchState: { ...tmpObj }

 });

 }

 }

 

 ).filter(item=> {

 return this.state.switchState[`check_${item.id}`] === 'N';

 });

 

 

灵活运用:

 

 

注意: 灵活使用find,findIndex,Filter,map等方法。

 

async函数就是对 Generator 函数的改进,只是将星号(*)替换成async,将yield替换成await,

 

 let submenu = await CustomizeAPI('menu', 'getSubmenuById', {

 

 downItem = async () => {

 

递归调用过滤内层数据!

 recurseDeleteNoUseSubmenu = subMenuData => {

 subMenuData = (subMenuData || []).filter(i=> i.checked !== false);

 for (leti = 0; i < subMenuData.length; ++i) {

 let tmp = subMenuData[i];

 tmp.menu = this.recurseDeleteNoUseSubmenu(tmp.menu);

 }

 return subMenuData;

 };

 

 

 const pos_arr = e.node.props.pos.split('-'); // todo: 这里的node.props.pos是什么?位置?

generator函数和promise

ES6 新增了 for..of 迭代器,它与 for..in 的区别是: 它返回的是值而不是 keys

 

findfilter区别:find返回一个对象,filter返回一个数组。

state中有什么名(state.cus)取决于combineReducers里传的键:

可以不传mapDispatch:

exportdefault connect(mapState)(Progress);

 

 productShortCustomizeFlagList.find(item=> item.value === text).title

antd中,不只是key不能重复,value也不可以:

 <Optionvalue={item.client_name}key={item.id}>

 {item.client_name}

 </Option>

map防止遍历空数组:

 {(projects_data || []).map((item, index) => (

Fiddler原理:

在本机开启一个http的代理服务器,然后它会转发所有的http请求和响应到最终的服务器

 

表格rowKey可以如下这样写?不应该对应于某个record的某个键吗?

递归遍历菜单内容!

1544084428(1)

 

this.props.form.getFieldDecorator(id, options):

经过 getFieldDecorator 包装的控件,表单控件会自动添加 value(或 valuePropName 指定的其他属性) onChange(或 trigger 指定的其他属性),数据同步将被 Form 接管,这会导致以下结果:

1.你不再需要也不应该用 onChange 来做同步,但还是可以继续监听 onChange 等事件。

2.你不能用控件的 value defaultValue 等属性来设置表单域的值,默认值可以用 getFieldDecorator 里的 initialValue

3.你不应该用 setState,可以使用 this.props.form.setFieldsValue 来动态改变表单值。

 

 

 

注意:获取表单值用 e.target.value

test = (e)=>{

console.log('test:',e.target.value)

}

 

 

{window.dataRight.map(item => item.data_code).includes('button') ? (

 

 

两个箭头函数写法

export const getServerList = (Offset, Limit) => dispatch => {

 

 

react好用组件大全:Awesome-react  https://github.com/enaqx/awesome-react

 

                   this.setState({

                            hasMore: count>0 && count<50

                   });

 

 

react要在本地运行,1.需要将BrowserRouter改成    HashRouter 2. 重新webpack打包编译运行

快速执行代码方法:

1.写入package.json某字段:  

"build": "./node_modules/.bin/webpack --progress --display-modules --profile --json > stats.json --colors —config webpack.production.config.js"

2.然后运行npm run build

 

 

通常dangerSetInnerHTML是和__html配套使用的,用来在一个标签中插入许多个标签

<div class="articleContainer" dangerouslySetInnerHTML={this.createMarkup()}></div>

         createMarkup() {

                   return {__html: this.state.newsItem.pagecontent};

         };

 

 

Antdesign 的表格中,选择的键最好命名为selectedRowKeys,不然可能出问题

 

属性设置也需要大写maxLength

 

视图的任何改变都会触发render

 

this.refs.childEdit.getEdited() 这种方式只能获取到放在组件内部的子组件

 

 

父组件调用子组件方法:this.refs.childref.func()

 

既能传参又不会马上被调用的方法:onClick={()=>{this.onEdit(text, record)} }

 

 

不推荐通过ref获取Input的值,如果非要通过ref获取的话,可以改成这样this.refs.email.refs.input.value,推荐监听onChange来获取值

 

  <Input ref='ipt' style={{margin:'0 10px'}} />  不是refs

 

组件的首字母必须大写!

 

给组件添加约束条件:

BodyIndex.propTypes = {

         userid: React.PropTypes.number.isRequired

};

                                    

<BodyChild{...this.props}id={4}handleChildValueChange={this.handleChildValueChange.bind(this)}/>

 

 

posted on 2019-02-18 15:11  joyful2  阅读(216)  评论(0编辑  收藏  举报

导航